其實很早以前就想寫這篇文章,一直拖到現在。
崩潰經歷一
我們公司做的是股票軟件,但集成的是第三方靜態庫(我們與第三方公司合作,他們提供股票服務,我們付費)。平時開發測試都好好的,結果上線幾天後就出現崩潰,說實話責任大半在我身上。
我的問題:過分信任文檔,沒做容錯處理,也就是沒對數據做相應的判斷。
下面附上代碼,說明崩潰原因。
第三方公司提供的數據錯亂,導致創建字典時個別 value 為 nil,從而引起崩潰
// 宏
#define CStringToOcString(cstr) [NSString stringWithCString:cstr encoding:GBK_ENCODE]
// 將每組數據都保存起來
NSMutableArray *returnArray = [NSMutableArray array];
for (int i = 0; i < recordM.count; i++) {
Withdrawqry_entrust_record *record = (Withdrawqry_entrust_record *)alloca(sizeof(Withdrawqry_entrust_record));
memset(record, 0x00, sizeof(Withdrawqry_entrust_record));
[[recordM objectAtIndex:i] getValue:record];
// 崩潰原因:創建字典時,有個別 value 為 nil
NSDictionary *param = @{
@"batch_no" : CStringToOcString(record->batch_no), // 委托批號
@"entrust_no" : CStringToOcString(record->entrust_no), // 委托編號
@"entrust_type" : @(record->entrust_type), // 委托類別 6 融資委托 7 融券委托
@"entrust_bs" : @(record->entrust_bs), // 買賣標志
@"stock_account" : CStringToOcString(record->stock_account), // 證券賬號
@"gdcode" : CStringToOcString(record->gdcode),
.....
};
解決辦法:在宏那裡加個判斷,若 value 為 nil 就直接賦值為 @""。
#define CStringToOcString(cstr) [NSString stringWithCString:cstr encoding:GBK_ENCODE] ? [NSString stringWithCString:cstr encoding:GBK_ENCODE] : @""
崩潰經歷二不多贅述,直接看代碼
// 服務器返回的日期格式為 20160301
// 我要把它轉換成 2016-03-01
/** 委托日期 */
NSMutableString *dateStrM = 服務器返回的數據;
[dateStrM insertString:@"-" atIndex:4];
[dateStrM insertString:@"-" atIndex:7];
就是這段代碼導致上線的程序崩潰,逼得我第二天緊急又發了一版。為何會崩?因為服務器返回的數據錯亂,返回了 0,字符串長度只有 1,卻往索引 4 的位置插入,程序必然崩潰。後來我在原代碼上加了個判斷:
if (dateStrM.length >= 8) {
[dateStrM insertString:@"-" atIndex:4];
[dateStrM insertString:@"-" atIndex:7];
}1、不要過分相信服務器返回的數據永遠正確。
2、處理數據時要做容錯,判斷之後再操作,這是良好的編程習慣。
眾所周知,Foundation 框架裡有大量常用方法帶有崩潰的潛在風險。對於一個已近竣工的項目,若當初沒做容錯又該怎麼辦?你總不會一行行去排查有沒有做容錯吧!——別逗了,老闆催你明天就上線!
那有沒有一種一勞永逸、無需改動原有代碼就能解決潛在崩潰的方法?
攔截那些存在潛在崩潰風險的方法,在攔截後的方法裡做相應處理,就能防止崩潰。
步驟:
1、通過 category 給類添加方法,用來替換原本存在潛在崩潰的方法。
2、利用 runtime 的方法交換技術,把系統方法替換成我們給類添加的新方法。
3、利用異常捕獲來防止程序崩潰,並做相應處理。
創建一個工具類 AvoidCrash,用來處理工序交換、定位會導致崩潰的代碼位置,並在控制台輸出錯誤信息……
AvoidCrash.h
//// AvoidCrash.h
// AvoidCrash
//
// Created by mac on 16/9/21.
// Copyright ? 2016年 chenfanfang. All rights reserved.
//
#import
#import
// 通知的名稱,若要獲取詳細的崩潰信息,請監聽此通知
#define AvoidCrashNotification @"AvoidCrashNotification"
#define AvoidCrashDefaultReturnNil @"This framework default is to return nil."
#define AvoidCrashDefaultIgnore @"This framework default is to ignore this operation to avoid crash."
@interface AvoidCrash : NSObject
/**
* become effective. You can call becomeEffective method in AppDelegate didFinishLaunchingWithOptions
*
* 開始生效。你可以在 AppDelegate 的 didFinishLaunchingWithOptions 方法中調用 becomeEffective 方法
*/
+ (void)becomeEffective;
+ (void)exchangeClassMethod:(Class)anClass method1Sel:(SEL)method1Sel method2Sel:(SEL)method2Sel;
+ (void)exchangeInstanceMethod:(Class)anClass method1Sel:(SEL)method1Sel method2Sel:(SEL)method2Sel;
+ (NSString *)getMainCallStackSymbolMessageWithCallStackSymbolStr:(NSString *)callStackSymbolStr;
+ (void)noteErrorWithException:(NSException *)exception defaultToDo:(NSString *)defaultToDo;
@end
AvoidCrash.m
//// AvoidCrash.m
// AvoidCrash
//
// Created by mac on 16/9/21.
// Copyright ? 2016年 chenfanfang. All rights reserved.
//
#import "AvoidCrash.h"
// category
#import "NSArray+AvoidCrash.h"
#import "NSMutableArray+AvoidCrash.h"
#import "NSDictionary+AvoidCrash.h"
#import "NSMutableDictionary+AvoidCrash.h"
#import "NSString+AvoidCrash.h"
#import "NSMutableString+AvoidCrash.h"
#define AvoidCrashSeparator @"================================================================"
#define AvoidCrashSeparatorWithFlag @"========================AvoidCrash Log=========================="
#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 AvoidCrash
/** 開始生效(進行方法的交換) */
+ (void)becomeEffective {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[NSArray avoidCrashExchangeMethod];
[NSMutableArray avoidCrashExchangeMethod];
[NSDictionary avoidCrashExchangeMethod];
[NSMutableDictionary avoidCrashExchangeMethod];
[NSString avoidCrashExchangeMethod];
[NSMutableString avoidCrashExchangeMethod];
});
}
/** 類方法的交換 */
+ (void)exchangeClassMethod:(Class)anClass method1Sel:(SEL)method1Sel method2Sel:(SEL)method2Sel {
Method method1 = class_getClassMethod(anClass, method1Sel);
Method method2 = class_getClassMethod(anClass, method2Sel);
method_exchangeImplementations(method1, method2);
}
/** 對象方法的交換 */
+ (void)exchangeInstanceMethod:(Class)anClass method1Sel:(SEL)method1Sel method2Sel:(SEL)method2Sel {
Method method1 = class_getInstanceMethod(anClass, method1Sel);
Method method2 = class_getInstanceMethod(anClass, method2Sel);
method_exchangeImplementations(method1, method2);
}
/** 獲取堆棧主要崩潰精簡化的信息<根據正則表達式匹配出來> */
+ (NSString *)getMainCallStackSymbolMessageWithCallStackSymbolStr:(NSString *)callStackSymbolStr {
// mainCallStackSymbolMsg 的格式為 +[類名 方法名] 或者 -[類名 方法名]
__block NSString *mainCallStackSymbolMsg = nil;
NSString *regularExpStr = @"[-\+\\[.+\\]";
NSRegularExpression *regularExp = [[NSRegularExpression alloc] initWithPattern:regularExpStr options:NSRegularExpressionCaseInsensitive error:nil];
[regularExp enumerateMatchesInString:callStackSymbolStr options:NSMatchingReportProgress range:NSMakeRange(0, callStackSymbolStr.length) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
if (result) {
mainCallStackSymbolMsg = [callStackSymbolStr substringWithRange:result.range];
*stop = YES;
}
}];
return mainCallStackSymbolMsg;
}
/** 提示崩潰的信息(控制台輸出、通知) */
+ (void)noteErrorWithException:(NSException *)exception defaultToDo:(NSString *)defaultToDo {
// 堆棧數據
NSArray *callStackSymbolsArr = [NSThread callStackSymbols];
// 獲取在哪個類的哪個方法中實例化的數組,字符串格式 -[類名 方法名] 或者 +[類名 方法名]
NSString *mainCallStackSymbolMsg = [AvoidCrash getMainCallStackSymbolMessageWithCallStackSymbolStr:callStackSymbolsArr[2]];
if (mainCallStackSymbolMsg == nil) {
mainCallStackSymbolMsg = @"崩潰方法定位失敗,請您查看函數調用棧來排查錯誤原因";
}
NSString *errorName = exception.name;
NSString *errorReason = exception.reason;
// 將 avoidCrash 去掉
errorReason = [errorReason stringByReplacingOccurrencesOfString:@"avoidCrash" withString:@""];
NSString *errorPlace = [NSString stringWithFormat:@"Error Place:%@",mainCallStackSymbolMsg];
NSString *logErrorMessage = [NSString stringWithFormat:@"\n\n%@\n\n%@\n%@\n%@\n%@\n\n%@\n\n",AvoidCrashSeparatorWithFlag,errorName,errorReason,errorPlace,defaultToDo,AvoidCrashSeparator];
NSLog(@"%@",&logErrorMessage);
NSDictionary *errorInfoDic = @{ key_errorName : errorName, key_errorReason : errorReason, key_errorPlace : errorPlace, key_defaultToDo : defaultToDo, key_exception : exception, key_callStackSymbols : callStackSymbolsArr };
// 將錯誤信息放進字典,以通知形式發送
[[NSNotificationCenter defaultCenter] postNotificationName:AvoidCrashNotification object:nil userInfo:errorInfoDic];
}
@end
再創建一個 NSDictionary 的分類,用來防止創建字典導致的崩潰。NSDictionary+AvoidCrash.h
//// NSDictionary+AvoidCrash.h
// AvoidCrash
//
// Created by mac on 16/9/21.
// Copyright ? 2016年 chenfanfang. All rights reserved.
//
#import
@interface NSDictionary (AvoidCrash)
+ (void)avoidCrashExchangeMethod;
@end
NSDictionary+AvoidCrash.m
先補充一個知識點:我們平常用 @{key : value} 快速創建字典,其實調用的是 dictionaryWithObjects:forKeys:count:,而它可能崩潰的原因是:key 數組中的 key 或 objects 中的 value 為空。
//// NSDictionary+AvoidCrash.m
// AvoidCrash
//
// Created by mac on 16/9/21.
// Copyright ? 2016年 chenfanfang. All rights reserved.
//
#import "NSDictionary+AvoidCrash.h"
#import "AvoidCrash.h"
@implementation NSDictionary (AvoidCrash)
+ (void)avoidCrashExchangeMethod {
[AvoidCrash exchangeClassMethod:self method1Sel:@selector(dictionaryWithObjects:forKeys:count:) method2Sel:@selector(avoidCrashDictionaryWithObjects:forKeys:count:)];
}
+ (instancetype)avoidCrashDictionaryWithObjects:(const id _Nonnull __unsafe_unretained *)objects forKeys:(const id_Nonnull __unsafe_unretained *)keys count:(NSUInteger)cnt {
id instance = nil;
@try {
instance = [self avoidCrashDictionaryWithObjects:objects forKeys:keys count:cnt];
}
@catch (NSException *exception) {
NSString *defaultToDo = @"This framework default is to remove nil key-values and instance a dictionary.";
[AvoidCrash noteErrorWithException:exception defaultToDo:defaultToDo];
// 處理錯誤的數據,然後重新初始化一個字典
NSUInteger index = 0;
id _Nonnull __unsafe_unretained newObjects[cnt];
id _Nonnull __unsafe_unretained newkeys[cnt];
for (int i = 0; i < cnt; i++) {
if (objects[i] && keys[i]) {
newObjects[index] = objects[i];
newkeys[index] = keys[i];
index++;
}
}
instance = [self avoidCrashDictionaryWithObjects:newObjects forKeys:newkeys count:index];
}
@finally {
return instance;
}
}
@end
正常情況下,若沒有上面的處理,如下代碼就會崩潰:
NSString *nilStr = nil;
NSDictionary *dict = @{ @"key" : nilStr };
崩潰截圖如下:

若做了如上的處理,就能避免崩潰:
[AvoidCrash becomeEffective];
控制台輸出截圖如下:

若想得到崩潰的詳細信息(監聽名為 AvoidCrashNotification 的通知即可),可以把這些信息傳到我們的服務器,或者在集成第三方 Crash 收集 SDK 時自定義信息。這樣既能防止崩潰,又能得知是哪段代碼導致的崩潰。
// 監聽通知 AvoidCrashNotification,獲取 AvoidCrash 捕獲的崩潰日志詳細信息
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealwithCrashMessage:) name:AvoidCrashNotification object:nil];
- (void)dealwithCrashMessage:(NSNotification *)note {
// 注意:所有信息都在 userInfo 中
// 你可以在這裡收集相應的崩潰信息進行處理(比如傳到自己服務器)
NSLog(@"\n\n在AppDelegate中 方法:dealwithCrashMessage打印\n\n\n\n\n%@\n\n\n\n",note.userInfo);
}
附上一張截圖,看看通知裡攜帶的崩潰信息長啥樣:

程序崩潰也有好處——它能讓開發者迅速意識到自己寫的代碼有問題,從而能及時修復 bug,當然這種好處僅限於開發階段。若一個上線的 App 出現崩潰,那問題可就大了(老闆不高興,後果很嚴重)。
個人建議:發佈 App 時再用上面介紹的方法防崩潰,開發階段最好別用。
上面只是舉例,更多防崩潰的方法請查看 GitHub 源碼 AvoidCrash,這是我最近寫的一個框架,大家可以集成到自己的項目裡。發佈 App 時在 appDelegate 的 didFinishLaunchingWithOptions 中調用 [AvoidCrash becomeEffective]; 即可,若要獲取崩潰信息,監聽通知就行。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[AvoidCrash becomeEffective];
// 監聽通知 AvoidCrashNotification,獲取 AvoidCrash 捕獲的崩潰日志詳細信息
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealwithCrashMessage:) name:AvoidCrashNotification object:nil];
return YES;
}
- (void)dealwithCrashMessage:(NSNotification *)note {
// 注意:所有信息都在 userInfo 中
// 你可以在這裡收集相應的崩潰信息進行處理(比如傳到自己服務器)
NSLog(@"\n\n在AppDelegate中 方法:dealwithCrashMessage打印\n\n\n\n\n%@\n\n\n\n",note.userInfo);
}同時希望大家能補充更多容易導致崩潰的方法,我好加進 AvoidCrash 框架,也歡迎大家一起維護。
最後,如果覺得有幫助,還請點個 star 支持一下。
修復上一版本部分方法無法攔截崩潰的 bug,具體修復項可查看 issues 和簡書留言。
優化崩潰代碼定位,定位更準確。
增加對 KVC 賦值的防崩潰處理。
增加對 NSAttributedString 的防崩潰處理。
增加對 NSMutableAttributedString 的防崩潰處理。
https://github.com/chenfanfang/AvoidCrash