该框架使用方法交换,将若干类的常见崩溃方法hook住,用try...catch...捕获Exception异常而避免崩溃。
比如对数组NSArray,针对数组越界错误类型,交换方法objectAtIndex:为下面的实现
- (id)__NSArray0AvoidCrashObjectAtIndex:(NSUInteger)index {
id object = nil;
@try {
object = [self __NSArray0AvoidCrashObjectAtIndex:index];
}
@catch (NSException *exception) {
NSString *defaultToDo = AvoidCrashDefaultReturnNil;
[AvoidCrash noteErrorWithException:exception defaultToDo:defaultToDo];
}
@finally {
return object;
}
}
@try中若数组越界了则会在@catch中捕获异常,然后处理异常。因为使用了try...catch,程序不会崩溃。
对捕获的异常做处理
+ (void)noteErrorWithException:(NSException *)exception defaultToDo:(NSString *)defaultToDo {
//堆栈数据
NSArray *callStackSymbolsArr = [NSThread callStackSymbols];
//获取在哪个类的哪个方法中实例化的数组 字符串格式 -[类名 方法名] 或者 +[类名 方法名]
NSString *mainCallStackSymbolMsg = [AvoidCrash 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];
NSString *logErrorMessage = [NSString stringWithFormat:@"\n\n%@\n\n%@\n%@\n%@\n%@",AvoidCrashSeparatorWithFlag, errorName, errorReason, errorPlace, defaultToDo];
logErrorMessage = [NSString stringWithFormat:@"%@\n\n%@\n\n",logErrorMessage,AvoidCrashSeparator];
AvoidCrashLog(@"%@",logErrorMessage);
//请忽略下面的赋值,目的只是为了能顺利上传到cocoapods
logErrorMessage = logErrorMessage;
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(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AvoidCrashNotification object:nil userInfo:errorInfoDic];
});
}
+ (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;
}
上面,[NSThread callStackSymbols]是获取到当前异常时的堆栈信息,类型是NSArray<NSString *>,例如:
<_NSCallStackArray 0x604000047500>(
0 AvoidCrashDemo 0x0000000109abfab5 +[AvoidCrash noteErrorWithException:defaultToDo:] + 133,
1 AvoidCrashDemo 0x0000000109abb6e7 -[NSObject(AvoidCrash) avoidCrashForwardInvocation:] + 311,
2 CoreFoundation 0x000000010acc3e08 ___forwarding___ + 760,
3 CoreFoundation 0x000000010acc3a88 _CF_forwarding_prep_0 + 120,
4 AvoidCrashDemo 0x0000000109aba62a -[ViewController testNoSelectorCrash] + 106,
5 AvoidCrashDemo 0x0000000109ab8b49 -[ViewController viewDidLoad] + 73,
6 UIKit 0x000000010b3618a5 -[UIViewController loadViewIfRequired] + 1235,
7 UIKit 0x000000010b361cf2 -[UIViewController view] + 27,
8 UIKit 0x000000010b22fb83 -[UIWindow addRootViewControllerViewIfPossible] + 122,
9 UIKit 0x000000010b23028b -[UIWindow _setHidden:forced:] + 294,
10 UIKit 0x000000010b243208 -[UIWindow makeKeyAndVisible] + 42,
)
然后用正则@"[-\+]\[.+\]"匹配出数组中每一条NSString中的方法,如-[ViewController testNoSelectorCrash],得到崩溃产生的方法调用列表。
将处理后得到的异常信息,如原因、地址等包装成一个字典,用通知发出去。可以在AppDelegate中监听通知获取异常信息,将信息上传到自己服务器记录。
我们一般使用的是Bugly捕获崩溃信息,但是使用AvoidCrash后异常被捕获,程序不再崩溃,Bugly不能再捕获到,这样对原本存在的错误无法知晓,万万不行。
发现Bugly有主动上报异常接口,[Bugly reportException:exception],so,只需要将AvoidCrash框架稍微改变一点,让最后发通知的时候将原本的Exception也传递一下,再在AppDelegate中监听通知,调用[Bugly reportException:exception]即可。
AvoidCrash除了能防止数组越界之类的崩溃之外,还能避免经典错误unrecognized selector sent to instance,开启选项后,在NSObject+AvoidCrash.m中,hook住消息转发第三部的那两个方法
// 消息转发第三部,捕获unrecognized selector sent to instance
- (NSMethodSignature *)avoidCrashMethodSignatureForSelector:(SEL)aSelector {
NSMethodSignature *ms = [self avoidCrashMethodSignatureForSelector:aSelector];
if (ms == nil) {
for (NSString *classStr in noneSelClassStrings) {
if ([self isKindOfClass:NSClassFromString(classStr)]) {
ms = [AvoidCrashStubProxy instanceMethodSignatureForSelector:@selector(proxyMethod)];
break;
}
}
}
return ms;
}
- (void)avoidCrashForwardInvocation:(NSInvocation *)anInvocation {
@try {
[self avoidCrashForwardInvocation:anInvocation];
} @catch (NSException *exception) {
NSString *defaultToDo = AvoidCrashDefaultIgnore;
[AvoidCrash noteErrorWithException:exception defaultToDo:defaultToDo];
} @finally {
}
}
使用AvoidCrash注意点:
1、使用[AvoidCrash setupNoneSelClassStringsArr:]]方法时,参数数组不能中不能有NSObject,否则会有些奇奇怪怪的bug,比如弹出键盘时会崩溃
2、数组中缺少一组交换方法,对象是__NSArrayM,方法是objectAtIndexedSubscript:
附录:
16年5月份的时候,那时刚接手别人一个藏家项目,崩溃太多了,集成Bugly一个版本,发现大多崩溃原因都是诸如数组越界、数组字典添加空对象、字符串截取子串NSRange越界等等,崩溃之多令人无言以对,逐个排查太费时间,遂干脆偷懒针对所有的此类bug写分类,原理跟AvoidCrash差不多,不过没有做Exception处理,仅仅是防止崩溃而已。
实现如数组分类
@implementation NSArray (Exception)
+(void)load{
SEL originalSelector = @selector(objectAtIndex:);
SEL swizzledSelector = @selector(by_objectAtIndex:);
Method originalMethod = class_getInstanceMethod(NSClassFromString(@"__NSArrayI"), originalSelector);
Method swizzledMethod = class_getInstanceMethod(NSClassFromString(@"__NSArrayI"), swizzledSelector);
method_exchangeImplementations(originalMethod, swizzledMethod);
}
- (id)by_objectAtIndex:(NSUInteger)index{
if (self.count == 0) {
NSLog(@"%s----数组为空",__FUNCTION__);
return nil;
}
if (index > self.count - 1) { // 防止数组越界崩溃
NSLog(@"%s----数组越界",__FUNCTION__);
return nil;
}
return [self by_objectAtIndex:index];
}
@end
我看了AvoidCrash第一个版本是16年10月,也许思路还借鉴了我的哈。