天天看点

IOS 捕获异常工具UncaughtExceptionHandler

开发iOS应用,解决Crash问题始终是一个难题。Crash分为两种,一种是由EXC_BAD_ACCESS引起的,原因是访问了不属于本进程的内存地址,有可能是访问已被释放的内存;另一种是未被捕获的Objective-C异常(NSException),导致程序向自身发送了SIGABRT信号而崩溃。其实对于未捕获的Objective-C异常,我们是有办法将它记录下来的,如果日志记录得当,能够解决绝大部分崩溃的问题。这里对于UI线程与后台线程分别说明。

一:在.h文件中编写

[plain] view plain copy

  1. @interface UncaughtExceptionHandler : NSObject{  
  2.     BOOL dismissed;  
  3. }  
  4. @end  
  5. void HandleException(NSException *exception);  
  6. void SignalHandler(int signal);  
  7. void InstallUncaughtExceptionHandler(void);  

二:在.m文件编写

[plain] view plain copy

  1. #import "UncaughtExceptionHandler.h"  
  2. #include <libkern/OSAtomic.h>  
  3. #include <execinfo.h>  
  4. //http://www.cocoachina.com/newbie/tutorial/2012/0829/4672.html  
  5. NSString * const UncaughtExceptionHandlerSignalExceptionName = @"UncaughtExceptionHandlerSignalExceptionName";  
  6. NSString * const UncaughtExceptionHandlerSignalKey = @"UncaughtExceptionHandlerSignalKey";  
  7. NSString * const UncaughtExceptionHandlerAddressesKey = @"UncaughtExceptionHandlerAddressesKey";  
  8. volatile int32_t UncaughtExceptionCount = 0;  
  9. const int32_t UncaughtExceptionMaximum = 10;  
  10. const NSInteger UncaughtExceptionHandlerSkipAddressCount = 4;  
  11. const NSInteger UncaughtExceptionHandlerReportAddressCount = 5;  
  12. @implementation UncaughtExceptionHandler  
  13. + (NSArray *)backtrace  
  14. {  
  15.      void* callstack[128];  
  16.      int frames = backtrace(callstack, 128);  
  17.      char **strs = backtrace_symbols(callstack, frames);  
  18.      int i;  
  19.      NSMutableArray *backtrace = [NSMutableArray arrayWithCapacity:frames];  
  20.      for (  
  21.         i = UncaughtExceptionHandlerSkipAddressCount;  
  22.         i < UncaughtExceptionHandlerSkipAddressCount +  
  23.             UncaughtExceptionHandlerReportAddressCount;  
  24.         i++)  
  25.      {  
  26.         [backtrace addObject:[NSString stringWithUTF8String:strs[i]]];  
  27.      }  
  28.      free(strs);  
  29.      return backtrace;  
  30. }  
  31. - (void)alertView:(UIAlertView *)anAlertView clickedButtonAtIndex:(NSInteger)anIndex  
  32. {  
  33.     if (anIndex == 0)  
  34.     {  
  35.         dismissed = YES;  
  36.     }else if (anIndex==1) {  
  37.         NSLog(@"ssssssss");  
  38.     }  
  39. }  
  40. - (void)validateAndSaveCriticalApplicationData  
  41. {  
  42. }  
  43. - (void)handleException:(NSException *)exception  
  44. {  
  45.     [self validateAndSaveCriticalApplicationData];  
  46.     UIAlertView *alert =  
  47.         [[[UIAlertView alloc]  
  48.             initWithTitle:NSLocalizedString(@"抱歉,程序出现了异常", nil)  
  49.             message:[NSString stringWithFormat:NSLocalizedString(  
  50.                 @"如果点击继续,程序有可能会出现其他的问题,建议您还是点击退出按钮并重新打开\n\n"  
  51.                 @"异常原因如下:\n%@\n%@", nil),  
  52.                 [exception reason],  
  53.                 [[exception userInfo] objectForKey:UncaughtExceptionHandlerAddressesKey]]  
  54.             delegate:self  
  55.             cancelButtonTitle:NSLocalizedString(@"退出", nil)  
  56.             otherButtonTitles:NSLocalizedString(@"继续", nil), nil]  
  57.         autorelease];  
  58.     [alert show];  
  59.     CFRunLoopRef runLoop = CFRunLoopGetCurrent();  
  60.     CFArrayRef allModes = CFRunLoopCopyAllModes(runLoop);  
  61.     while (!dismissed)  
  62.     {  
  63.         for (NSString *mode in (NSArray *)allModes)  
  64.         {  
  65.             CFRunLoopRunInMode((CFStringRef)mode, 0.001, false);  
  66.         }  
  67.     }  
  68.     CFRelease(allModes);  
  69.     NSSetUncaughtExceptionHandler(NULL);  
  70.     signal(SIGABRT, SIG_DFL);  
  71.     signal(SIGILL, SIG_DFL);  
  72.     signal(SIGSEGV, SIG_DFL);  
  73.     signal(SIGFPE, SIG_DFL);  
  74.     signal(SIGBUS, SIG_DFL);  
  75.     signal(SIGPIPE, SIG_DFL);  
  76.     if ([[exception name] isEqual:UncaughtExceptionHandlerSignalExceptionName])  
  77.     {  
  78.         kill(getpid(), [[[exception userInfo] objectForKey:UncaughtExceptionHandlerSignalKey] intValue]);  
  79.     }  
  80.     else  
  81.     {  
  82.         [exception raise];  
  83.     }  
  84. }  
  85. @end  
  86. void HandleException(NSException *exception)  
  87. {  
  88.     int32_t exceptionCount = OSAtomicIncrement32(&UncaughtExceptionCount);  
  89.     if (exceptionCount > UncaughtExceptionMaximum)  
  90.     {  
  91.         return;  
  92.     }  
  93.     NSArray *callStack = [UncaughtExceptionHandler backtrace];  
  94.     NSMutableDictionary *userInfo =  
  95.         [NSMutableDictionary dictionaryWithDictionary:[exception userInfo]];  
  96.     [userInfo  
  97.         setObject:callStack  
  98.         forKey:UncaughtExceptionHandlerAddressesKey];  
  99.     [[[[UncaughtExceptionHandler alloc] init] autorelease]  
  100.         performSelectorOnMainThread:@selector(handleException:)  
  101.         withObject:  
  102.             [NSException  
  103.                 exceptionWithName:[exception name]  
  104.                 reason:[exception reason]  
  105.                 userInfo:userInfo]  
  106.         waitUntilDone:YES];  
  107. }  
  108. void SignalHandler(int signal)  
  109. {  
  110.     int32_t exceptionCount = OSAtomicIncrement32(&UncaughtExceptionCount);  
  111.     if (exceptionCount > UncaughtExceptionMaximum)  
  112.     {  
  113.         return;  
  114.     }  
  115.     NSMutableDictionary *userInfo =  
  116.         [NSMutableDictionary  
  117.             dictionaryWithObject:[NSNumber numberWithInt:signal]  
  118.             forKey:UncaughtExceptionHandlerSignalKey];  
  119.     NSArray *callStack = [UncaughtExceptionHandler backtrace];  
  120.     [userInfo  
  121.         setObject:callStack  
  122.         forKey:UncaughtExceptionHandlerAddressesKey];  
  123.     [[[[UncaughtExceptionHandler alloc] init] autorelease]  
  124.         performSelectorOnMainThread:@selector(handleException:)  
  125.         withObject:  
  126.             [NSException  
  127.                 exceptionWithName:UncaughtExceptionHandlerSignalExceptionName  
  128.                 reason:  
  129.                     [NSString stringWithFormat:  
  130.                         NSLocalizedString(@"Signal %d was raised.", nil),  
  131.                         signal]  
  132.                 userInfo:  
  133.                     [NSDictionary  
  134.                         dictionaryWithObject:[NSNumber numberWithInt:signal]  
  135.                         forKey:UncaughtExceptionHandlerSignalKey]]  
  136.         waitUntilDone:YES];  
  137. }  
  138. void InstallUncaughtExceptionHandler(void)  
  139. {  
  140.     NSSetUncaughtExceptionHandler(&HandleException);  
  141.     signal(SIGABRT, SignalHandler);  
  142.     signal(SIGILL, SignalHandler);  
  143.     signal(SIGSEGV, SignalHandler);  
  144.     signal(SIGFPE, SignalHandler);  
  145.     signal(SIGBUS, SignalHandler);  
  146.     signal(SIGPIPE, SignalHandler);  
  147. }  

三:最后在AppDelegate中创建

[plain] view plain copy

  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{  
  2.   InstallUncaughtExceptionHandler();  
  3.     self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];  
  4.     // Override point for customization after application launch.  
  5.   self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];  
  6.   self.window.rootViewController = self.viewController;  
  7.     [self.window makeKeyAndVisible];  
  8.     return YES;  
  9. }  

四:最后的测试

[plain] view plain copy

  1. - (IBAction)onclcko:(id)sender {  
  2.    //  [alert show];  
  3.     NSArray *arry=[NSArray arrayWithObject:@"sss"];  
  4.     NSLog(@"%@",[arry objectAtIndex:1]);  
  5. }  

五:结果

2014-05-29 18:03:44.554 bengkui[39548:60b] Debug details follow:

*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]

(

    "4   libc++abi.dylib                     0x05741f60 _ZSt11__terminatePFvvE + 14",

    "5   libc++abi.dylib                     0x05741b97 __cxa_rethrow + 103",

    "6   libobjc.A.dylib                     0x0156fa86 objc_exception_rethrow + 47",

    "7   CoreFoundation                      0x023dca65 CFRunLoopRunSpecific + 613",

    "8   CoreFoundation                      0x023dc7eb CFRunLoopRunInMode + 123"

)