一. 捕获Crash异常信息
第1种异常(NSException)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSSetUncaughtExceptionHandler(&CrashExceptionHandler);
return YES;
}
void CrashExceptionHandler(NSException *exception) {
NSArray<NSString *> *callStack = [exception callStackSymbols];
NSString *reason = [exception reason];
NSString *name = [exception name];
NSLog(@"原因:%@\n名称:%@\n调用栈:%@", reason, name, callStack);
}
第2种异常(收到系统发出的SIGXXX信号导致Crash)
#include <execinfo.h>(需要引入的函数库)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
signal(SIGABRT, SignalExceptionHandler);
signal(SIGILL, SignalExceptionHandler);
signal(SIGSEGV, SignalExceptionHandler);
signal(SIGFPE, SignalExceptionHandler);
signal(SIGBUS, SignalExceptionHandler);
signal(SIGPIPE, SignalExceptionHandler);
return YES;
}
void SignalExceptionHandler(int signal)
{
NSArray *callStack = [AppDelegate backtrace];
NSLog(@"信号捕获崩溃,堆栈信息:%@",callStack);
NSString *name = @"LMSignalException";
NSString *reason = [NSString stringWithFormat:@"signal %d was raised",signal];
NSLog(@"名称:%@\n原因:%@", name, reason);
}
+ (NSArray *)backtrace {
void* callstack[128];
int frames = backtrace(callstack, 128);
char **strs = backtrace_symbols(callstack, frames);
NSMutableArray *backtrace = [NSMutableArray arrayWithCapacity:frames];
for (int i = 0; i < frames; i++) {
[backtrace addObject:[NSString stringWithUTF8String:strs[i]]];
}
free(strs);
return backtrace;
}
备注:仅仅是捕获异常可能不能满足程序的需求,所以再推荐使用AvoidCrash
二. 防止程序Crash + 捕获Crash异常信息
AvoidCrash的使用方法写的很详细,作者很认真,点赞!