iOS-runtime 入門和簡單用法.

開端

因為最近APP總會有很多Crash信息定位在主函數(shù)main里面,所以發(fā)現(xiàn)很多出現(xiàn)的BUG不好定位修改,所以就想通過iOS的runtime機制,自己寫個防crash機制,并且收集信息.
當然通過google,和百度的一系列查詢后,大概Copy了個簡單的Crash信息防護,和收集系統(tǒng),借鑒的資料有網(wǎng)易一個團隊的大白系統(tǒng) http://www.reibang.com/p/02157577d4e7 (我記得他們說要開源,等了好久,還沒有消息),
還有chenfanfang的很多文章 和春田花花幼兒園的簡書

通過runtime如何防止Crash

相信做個iOS開發(fā)的朋友都知道,OC是個動態(tài)語言,其中很主要的就是消息機制,在運行的過程中通過消息機制動態(tài)的調(diào)用對應函數(shù).所以我們就可以想辦法在處理對應函數(shù)的時候,替換掉系統(tǒng)的方法來執(zhí)行.
如果出現(xiàn)錯誤,我們可以把錯誤信息獲取到,同時讓Crash的方法不在繼續(xù)執(zhí)行,無效化.

示例代碼

比如我們創(chuàng)建個可變數(shù)組,之后再插入數(shù)據(jù),因為數(shù)組越界會造成程序crash,并且控制臺提示信息.

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

控制臺信息

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

接下來就是我們創(chuàng)造個類,來替換掉系統(tǒng)NSMutableArray的setObject 方法

#import <Foundation/Foundation.h>

@interface NSMutableArray (Crash)

@end

@implementation 就是對應的作用域,@implementation NSMutableArray意思就是對應所有可變數(shù)組.

#import "NSMuableArray+Crash.h"
#import <objc/runtime.h>

#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
{
    // 執(zhí)行一次.
    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 {
        // 因為交換過方法,所以在此調(diào)用這個其實是調(diào)用的系統(tǒng)原先的方法.
        [self KsetObject:object atIndexedSubscript:index];
    } @catch (NSException *exception) {
        [self noteErrorWithException:exception defaultToDo:AvoidCrashDefaultIgnore];
    } @finally {
        
        // 這里面的代碼一定會執(zhí)行.
    }
    
}

/**
 *  獲取堆棧主要崩潰精簡化的信息<根據(jù)正則表達式匹配出來>
 *
 *  @param callStackSymbols 堆棧主要崩潰信息
 *
 *  @return 堆棧主要崩潰精簡化的信息
 */

- (NSString *)getMainCallStackSymbolMessageWithCallStackSymbols:(NSArray<NSString *> *)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 {
    
    //堆棧數(shù)據(jù)
    NSArray *callStackSymbolsArr = [NSThread callStackSymbols];
    
    //獲取在哪個類的哪個方法中實例化的數(shù)組  字符串格式 -[類名 方法名]  或者 +[類名 方法名]
    NSString *mainCallStackSymbolMsg = [self getMainCallStackSymbolMessageWithCallStackSymbols:callStackSymbolsArr];
    
    if (mainCallStackSymbolMsg == nil) {
        
        mainCallStackSymbolMsg = @"崩潰方法定位失敗,請您查看函數(shù)調(diào)用棧來排查錯誤原因";
        
    }
    
    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
                                   };
    
    //將錯誤信息放在字典里,用通知的形式發(fā)送出去
    dispatch_async(dispatch_get_main_queue(), ^{
        
        NSLog(@"%@",errorInfoDic);
    });
    
    
}


@end

數(shù)組越界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 <redacted> + 1040
    4   UIKit                               0x000000018d2fcd5c <redacted> + 28
    5   UIKit                               0x000000018d303a8c <redacted> + 136
    6   UIKit                               0x000000018d300cf8 <redacted> + 272
    7   UIKit                               0x000000018d370664 <redacted> + 48
    8   UIKit                               0x000000018d55f3a4 <redacted> + 3616
    9   UIKit                               0x000000018d56414c <redacted> + 1712
    10  UIKit                               0x000000018d7e5780 <redacted> + 136
    11  UIKit                               0x000000018daaaec4 <redacted> + 160
    12  UIKit                               0x000000018d7e567c <redacted> + 252
    13  UIKit                               0x000000018d7e5b20 <redacted> + 756
    14  UIKit                               0x000000018df26978 <redacted> + 244
    15  UIKit                               0x000000018df2682c <redacted> + 448
    16  UIKit                               0x000000018dcb56b8 <redacted> + 220
    17  UIKit                               0x000000018de4262c _performActionsWithDelayForTransitionContext + 112
    18  UIKit                               0x000000018dcb5568 <redacted> + 252
    19  UIKit                               0x000000018daaa544 <redacted> + 364
    20  UIKit                               0x000000018d562890 <redacted> + 540
    21  UIKit                               0x000000018d953214 <redacted> + 364
    22  FrontBoardServices                  0x0000000185ea2968 <redacted> + 364
    23  FrontBoardServices                  0x0000000185eab270 <redacted> + 224
    24  libdispatch.dylib                   0x00000001009d18ac _dispatch_client_callout + 16
    25  libdispatch.dylib                   0x00000001009dde84 _dispatch_block_invoke_direct + 232
    26  FrontBoardServices                  0x0000000185ed6b04 <redacted> + 36
    27  FrontBoardServices                  0x0000000185ed67a8 <redacted> + 404
    28  FrontBoardServices                  0x0000000185ed6d44 <redacted> + 56
    29  CoreFoundation                      0x00000001837e0a80 <redacted> + 24
    30  CoreFoundation                      0x00000001837e0a00 <redacted> + 88
    31  CoreFoundation                      0x00000001837e0288 <redacted> + 204
    32  CoreFoundation                      0x00000001837dde60 <redacted> + 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 <redacted> + 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內(nèi)做統(tǒng)計事件,比如點擊,比如頁面的進入次數(shù),這些其實可以通過在項目初期創(chuàng)建個很好的基類容器來實現(xiàn),但是如果后期加入,并且初期的基類并沒有很好的構造,這個時候就會發(fā)現(xiàn)runtime有很大的用處.
這篇文章其實主要就是用代碼來展示,主要原因還是作者很少寫文章,也不太會措辭,哈哈哈.

統(tǒng)計頁面進入示例

可以通過改寫系統(tǒng)的- (void)viewWillAppear:(BOOL)animated 方法.

#import "Statistics+ViewController.h"
#import <objc/runtime.h>

@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的方法,所以交換方法要先交換系統(tǒng)的Delegate方法,交換成功后再交換Cell的DidSelect方法.

#import "DJ+TableView.h"
#import <objc/runtime.h>
#import <objc/message.h>

@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<UITableViewDelegate>)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雖然很多人感覺是動用了系統(tǒng)層的語法,怕在使用過程中遇到未知的問題,但是我在使用過程中感覺還是利大于弊,需要對全局進行操作的時候方便很多.并且runtime所對應的AOP編程方式,也更適用于做這種架構的編程.

Demo地址

KaiPisces/RuntimeDemo

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末笛粘,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子挟冠,更是在濱河造成了極大的恐慌鄙早,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,366評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件裂垦,死亡現(xiàn)場離奇詭異颠毙,居然都是意外死亡斯入,警方通過查閱死者的電腦和手機拿霉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,521評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來咱扣,“玉大人绽淘,你說我怎么就攤上這事∧治保” “怎么了沪铭?”我有些...
    開封第一講書人閱讀 165,689評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長偏瓤。 經(jīng)常有香客問我杀怠,道長,這世上最難降的妖魔是什么厅克? 我笑而不...
    開封第一講書人閱讀 58,925評論 1 295
  • 正文 為了忘掉前任赔退,我火速辦了婚禮,結果婚禮上证舟,老公的妹妹穿的比我還像新娘硕旗。我一直安慰自己,他們只是感情好女责,可當我...
    茶點故事閱讀 67,942評論 6 392
  • 文/花漫 我一把揭開白布漆枚。 她就那樣靜靜地躺著,像睡著了一般抵知。 火紅的嫁衣襯著肌膚如雪墙基。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,727評論 1 305
  • 那天刷喜,我揣著相機與錄音残制,去河邊找鬼。 笑死掖疮,一個胖子當著我的面吹牛初茶,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播氮墨,決...
    沈念sama閱讀 40,447評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼纺蛆,長吁一口氣:“原來是場噩夢啊……” “哼吐葵!你這毒婦竟也來了规揪?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,349評論 0 276
  • 序言:老撾萬榮一對情侶失蹤温峭,失蹤者是張志新(化名)和其女友劉穎猛铅,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體凤藏,經(jīng)...
    沈念sama閱讀 45,820評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡奸忽,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,990評論 3 337
  • 正文 我和宋清朗相戀三年堕伪,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片栗菜。...
    茶點故事閱讀 40,127評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出论熙,到底是詐尸還是另有隱情缕题,我是刑警寧澤,帶...
    沈念sama閱讀 35,812評論 5 346
  • 正文 年R本政府宣布而咆,位于F島的核電站霍比,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏暴备。R本人自食惡果不足惜悠瞬,卻給世界環(huán)境...
    茶點故事閱讀 41,471評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望涯捻。 院中可真熱鬧浅妆,春花似錦、人聲如沸障癌。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,017評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽混弥。三九已至趴乡,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間蝗拿,已是汗流浹背晾捏。 一陣腳步聲響...
    開封第一講書人閱讀 33,142評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留哀托,地道東北人惦辛。 一個月前我還...
    沈念sama閱讀 48,388評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像仓手,于是被迫代替她去往敵國和親胖齐。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,066評論 2 355

推薦閱讀更多精彩內(nèi)容