iOS-runtime 入门和简单用法.

开端

因为最近APP总会有很多Crash信息定位在主函数main里面,所以发现很多出现的BUG不好定位修改,所以就想通过iOS的runtime机制,自己写个防crash机制,并且收集信息.
当然通过google,和百度的一系列查询后,大概Copy了个简单的Crash信息防护,和收集系统,借鉴的资料有网易一个团队的大白系统 http://www.jianshu.com/p/02157577d4e7 (我记得他们说要开源,等了好久,还没有消息),
还有chenfanfang的很多文章 和春田花花幼儿园的

通过runtime如何防止Crash

相信做个iOS开发的朋友都知道,OC是个动态语言,其中很主要的就是消息机制,在运行的过程中通过消息机制动态的调用对应函数.所以我们就可以想办法在处理对应函数的时候,替换掉系统的方法来执行.
如果出现错误,我们可以把错误信息获取到,同时让Crash的方法不在继续执行,无效化.

示例代码

比如我们创建个可变数组,之后再插入数据,因为数组越界会造成程序crash,并且控制台提示信息.

NSMutableArray *muArray = [NSMutableArray new];
[muArray setObject:@"crash" atIndexedSubscript:1];

控制台信息

reason: '*** -[__NSArrayM setObject:atIndexedSubscript:]: index 1 beyond bounds for empty array'

接下来就是我们创造个类,来替换掉系统NSMutableArray的setObject 方法

#import 

@interface NSMutableArray (Crash)

@end

@implementation 就是对应的作用域,@implementation NSMutableArray意思就是对应所有可变数组.

#import "NSMuableArray+Crash.h"
#import 

#define AvoidCrashSeparator         @"================================================================"
#define AvoidCrashSeparatorWithFlag @"========================AvoidCrash Log=========================="
#define AvoidCrashDefaultIgnore     @"This framework default is to ignore this operation to avoid crash."

#define key_errorName        @"errorName"
#define key_errorReason      @"errorReason"
#define key_errorPlace       @"errorPlace"
#define key_defaultToDo      @"defaultToDo"
#define key_callStackSymbols @"callStackSymbols"
#define key_exception        @"exception"

@implementation NSMutableArray (Crash)

+(void)load
{
    // 执行一次.
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        Class muArrayClass = NSClassFromString(@"__NSArrayM");
        SEL originalMethodSel = @selector(setObject:atIndexedSubscript:);
        SEL swizzledMethodSel = @selector(KsetObject:atIndexedSubscript:);
        
        Method originalMethod = class_getInstanceMethod(muArrayClass, originalMethodSel);
        Method swizzledMethod = class_getInstanceMethod(muArrayClass, swizzledMethodSel);
        
        BOOL didAddMethod =
        class_addMethod(muArrayClass,
                        originalMethodSel,
                        method_getImplementation(swizzledMethod),
                        method_getTypeEncoding(swizzledMethod));
        
        if (didAddMethod) {
            class_replaceMethod(muArrayClass,
                                originalMethodSel,
                                method_getImplementation(originalMethod),
                                method_getTypeEncoding(originalMethod));
        }
        
        else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
        
    });
}


- (void)KsetObject:(id)object atIndexedSubscript:(NSInteger)index{
    
    
    // 可能crash的方法,并且获取crash的信息
    @try {
        // 因为交换过方法,所以在此调用这个其实是调用的系统原先的方法.
        [self KsetObject:object atIndexedSubscript:index];
    } @catch (NSException *exception) {
        [self noteErrorWithException:exception defaultToDo:AvoidCrashDefaultIgnore];
    } @finally {
        
        // 这里面的代码一定会执行.
    }
    
}

/**
 *  获取堆栈主要崩溃精简化的信息<根据正则表达式匹配出来>
 *
 *  @param callStackSymbols 堆栈主要崩溃信息
 *
 *  @return 堆栈主要崩溃精简化的信息
 */

- (NSString *)getMainCallStackSymbolMessageWithCallStackSymbols:(NSArray *)callStackSymbols {
    
    //mainCallStackSymbolMsg的格式为   +[类名 方法名]  或者 -[类名 方法名]
    __block NSString *mainCallStackSymbolMsg = nil;
    
    //匹配出来的格式为 +[类名 方法名]  或者 -[类名 方法名]
    NSString *regularExpStr = @"[-\\+]\\[.+\\]";
    
    
    NSRegularExpression *regularExp = [[NSRegularExpression alloc] initWithPattern:regularExpStr options:NSRegularExpressionCaseInsensitive error:nil];
    
    
    for (int index = 2; index < callStackSymbols.count; index++) {
        NSString *callStackSymbol = callStackSymbols[index];
        
        [regularExp enumerateMatchesInString:callStackSymbol options:NSMatchingReportProgress range:NSMakeRange(0, callStackSymbol.length) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
            if (result) {
                NSString* tempCallStackSymbolMsg = [callStackSymbol substringWithRange:result.range];
                
                //get className
                NSString *className = [tempCallStackSymbolMsg componentsSeparatedByString:@" "].firstObject;
                className = [className componentsSeparatedByString:@"["].lastObject;
                
                NSBundle *bundle = [NSBundle bundleForClass:NSClassFromString(className)];
                
                //filter category and system class
                if (![className hasSuffix:@")"] && bundle == [NSBundle mainBundle]) {
                    mainCallStackSymbolMsg = tempCallStackSymbolMsg;
                    
                }
                *stop = YES;
            }
        }];
        
        if (mainCallStackSymbolMsg.length) {
            break;
        }
    }
    
    return mainCallStackSymbolMsg;
}


/**
 *  提示崩溃的信息(控制台输出、通知)
 *
 *  @param exception   捕获到的异常
 *  @param defaultToDo 这个框架里默认的做法
 */
- (void)noteErrorWithException:(NSException *)exception defaultToDo:(NSString *)defaultToDo {
    
    //堆栈数据
    NSArray *callStackSymbolsArr = [NSThread callStackSymbols];
    
    //获取在哪个类的哪个方法中实例化的数组  字符串格式 -[类名 方法名]  或者 +[类名 方法名]
    NSString *mainCallStackSymbolMsg = [self getMainCallStackSymbolMessageWithCallStackSymbols:callStackSymbolsArr];
    
    if (mainCallStackSymbolMsg == nil) {
        
        mainCallStackSymbolMsg = @"崩溃方法定位失败,请您查看函数调用栈来排查错误原因";
        
    }
    
    NSString *errorName = exception.name;
    NSString *errorReason = exception.reason;
    //errorReason 可能为 -[__NSCFConstantString avoidCrashCharacterAtIndex:]: Range or index out of bounds
    //将avoidCrash去掉
    errorReason = [errorReason stringByReplacingOccurrencesOfString:@"avoidCrash" withString:@""];
    
    NSString *errorPlace = [NSString stringWithFormat:@"Error Place:%@",mainCallStackSymbolMsg];
    
    NSDictionary *errorInfoDic = @{
                                   key_errorName        : errorName,
                                   key_errorReason      : errorReason,
                                   key_errorPlace       : errorPlace,
                                   key_defaultToDo      : defaultToDo,
                                   key_exception        : exception,
                                   key_callStackSymbols : callStackSymbolsArr
                                   };
    
    //将错误信息放在字典里,用通知的形式发送出去
    dispatch_async(dispatch_get_main_queue(), ^{
        
        NSLog(@"%@",errorInfoDic);
    });
    
    
}


@end

数组越界APP并没有Crash,打印exception信息

2017-07-27 10:21:00.099509+0800 CrashDemo[6760:791263] {
    callStackSymbols = (
    0   CrashDemo                           0x000000010091bf10 -[NSMutableArray(NSMutableArray_Crash) noteErrorWithException:defaultToDo:] + 144
    1   CrashDemo                           0x000000010091b634 -[NSMutableArray(NSMutableArray_Crash) KsetObject:atIndexedSubscript:] + 296
    2   CrashDemo                           0x000000010091b014 -[ViewController viewDidLoad] + 144
    3   UIKit                               0x000000018d2fd184  + 1040
    4   UIKit                               0x000000018d2fcd5c  + 28
    5   UIKit                               0x000000018d303a8c  + 136
    6   UIKit                               0x000000018d300cf8  + 272
    7   UIKit                               0x000000018d370664  + 48
    8   UIKit                               0x000000018d55f3a4  + 3616
    9   UIKit                               0x000000018d56414c  + 1712
    10  UIKit                               0x000000018d7e5780  + 136
    11  UIKit                               0x000000018daaaec4  + 160
    12  UIKit                               0x000000018d7e567c  + 252
    13  UIKit                               0x000000018d7e5b20  + 756
    14  UIKit                               0x000000018df26978  + 244
    15  UIKit                               0x000000018df2682c  + 448
    16  UIKit                               0x000000018dcb56b8  + 220
    17  UIKit                               0x000000018de4262c _performActionsWithDelayForTransitionContext + 112
    18  UIKit                               0x000000018dcb5568  + 252
    19  UIKit                               0x000000018daaa544  + 364
    20  UIKit                               0x000000018d562890  + 540
    21  UIKit                               0x000000018d953214  + 364
    22  FrontBoardServices                  0x0000000185ea2968  + 364
    23  FrontBoardServices                  0x0000000185eab270  + 224
    24  libdispatch.dylib                   0x00000001009d18ac _dispatch_client_callout + 16
    25  libdispatch.dylib                   0x00000001009dde84 _dispatch_block_invoke_direct + 232
    26  FrontBoardServices                  0x0000000185ed6b04  + 36
    27  FrontBoardServices                  0x0000000185ed67a8  + 404
    28  FrontBoardServices                  0x0000000185ed6d44  + 56
    29  CoreFoundation                      0x00000001837e0a80  + 24
    30  CoreFoundation                      0x00000001837e0a00  + 88
    31  CoreFoundation                      0x00000001837e0288  + 204
    32  CoreFoundation                      0x00000001837dde60  + 1048
    33  CoreFoundation                      0x00000001836ff9dc CFRunLoopRunSpecific + 436
    34  GraphicsServices                    0x000000018555cfac GSEventRunModal + 100
    35  UIKit                               0x000000018d360ef0 UIApplicationMain + 208
    36  CrashDemo                           0x000000010091c418 main + 124
    37  libdyld.dylib                       0x000000018321ea14  + 4
);
    defaultToDo = "This framework default is to ignore this operation to avoid crash.";
    errorName = NSRangeException;
    errorPlace = "Error Place:-[ViewController viewDidLoad]";
    errorReason = "*** -[__NSArrayM setObject:atIndexedSubscript:]: index 1 beyond bounds for empty array";
    exception = "*** -[__NSArrayM setObject:atIndexedSubscript:]: index 1 beyond bounds for empty array";
}

这个信息通过正则表达式处理,可以获取到自己想要的信息,包括造成崩溃的方法,具体位置.
我的这个处理方法是从chenfanfang那里copy的
个人感觉在crash的处理方面用起来还是很方便的,有时候需要在APP内做统计事件,比如点击,比如页面的进入次数,这些其实可以通过在项目初期创建个很好的基类容器来实现,但是如果后期加入,并且初期的基类并没有很好的构造,这个时候就会发现runtime有很大的用处.
这篇文章其实主要就是用代码来展示,主要原因还是作者很少写文章,也不太会措辞,哈哈哈.

统计页面进入示例

可以通过改写系统的- (void)viewWillAppear:(BOOL)animated 方法.

#import "Statistics+ViewController.h"
#import 

@implementation UIViewController (Statistics_ViewController)


+(void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        Method originalMethod = class_getInstanceMethod([self class], @selector(viewWillAppear:));
        Method swizzledMethod = class_getInstanceMethod([self class], @selector(KviewWillAppear:));
        
        method_exchangeImplementations(originalMethod, swizzledMethod);
        
    });
}

- (void)KviewWillAppear:(BOOL)animated
{
    [self KviewWillAppear:animated];
    NSLog(@"进入%@",[self class]);
}

拦截tableview的点击方法

tableview点击方法因为是tableViewDelegate的方法,所以交换方法要先交换系统的Delegate方法,交换成功后再交换Cell的DidSelect方法.

#import "DJ+TableView.h"
#import 
#import 

@implementation UITableView (DJ_TableView)

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        Method originalMethod = class_getInstanceMethod(self, @selector(setDelegate:));
        Method swizzledMethod = class_getInstanceMethod(self, @selector(DJsetDelegate:));
        
        BOOL didAddMethod =
        class_addMethod(self,
                        @selector(setDelegate:),
                        method_getImplementation(swizzledMethod),
                        method_getTypeEncoding(swizzledMethod));
        
        if (didAddMethod) {
            class_replaceMethod(self,
                                @selector(DJsetDelegate:),
                                method_getImplementation(originalMethod),
                                method_getTypeEncoding(originalMethod));
        }
        
        else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });
    
}

- (void)DJsetDelegate:(id)delegate
{
    [self DJsetDelegate:delegate];
    
    if (class_addMethod([delegate class], NSSelectorFromString(@"DJdidSelectRowAtIndexPath"), (IMP)DJdidSelectRowAtIndexPath, "v@:@@")) {
        Method didSelectOriginalMethod = class_getInstanceMethod([delegate class], NSSelectorFromString(@"DJdidSelectRowAtIndexPath"));
        Method didSelectSwizzledMethod = class_getInstanceMethod([delegate class], @selector(tableView:didSelectRowAtIndexPath:));
        
        method_exchangeImplementations(didSelectOriginalMethod, didSelectSwizzledMethod);
    }
    
}

void DJdidSelectRowAtIndexPath(id self, SEL _cmd, id tableView, id indexPath)
{
    SEL selector = NSSelectorFromString(@"DJdidSelectRowAtIndexPath");
    ((void(*)(id, SEL, id, id))objc_msgSend)(self, selector, tableView, indexPath);
    NSLog(@"点击了");
}

@end

runtime虽然很多人感觉是动用了系统层的语法,怕在使用过程中遇到未知的问题,但是我在使用过程中感觉还是利大于弊,需要对全局进行操作的时候方便很多.并且runtime所对应的AOP编程方式,也更适用于做这种架构的编程.

Demo地址

KaiPisces/RuntimeDemo

你可能感兴趣的:(iOS-runtime 入门和简单用法.)