怎么做離線網(wǎng)站網(wǎng)站注冊要多少錢
為了在iOS中捕獲和處理未捕獲的Objective-C異常和系統(tǒng)信號引起的崩潰,可以使用`NSSetUncaughtExceptionHandler`和標(biāo)準(zhǔn)的Unix信號處理機(jī)制來實(shí)現(xiàn)。這能幫助你記錄絕大部分的崩潰信息。以下是詳細(xì)的實(shí)現(xiàn)步驟和代碼示例:
一、系統(tǒng)崩潰處理
通過`NSSetUncaughtExceptionHandler`捕獲未處理的Objective-C異常:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>@interface UncaughtExceptionHandler : NSObject+ (void)installUncaughtExceptionHandler:(BOOL)install showAlert:(BOOL)showAlert;@end#import "UncaughtExceptionHandler.h"
#include <libkern/OSAtomic.h>
#include <execinfo.h>NSString * const UncaughtExceptionHandlerSignalExceptionName = @"UncaughtExceptionHandlerSignalExceptionName";
NSString * const UncaughtExceptionHandlerSignalKey = @"UncaughtExceptionHandlerSignalKey";
NSString * const UncaughtExceptionHandlerAddressesKey = @"UncaughtExceptionHandlerAddressesKey";
volatile int32_t UncaughtExceptionCount = 0;
const int32_t UncaughtExceptionMaximum = 10;
static BOOL showAlertView = nil;void HandleException(NSException *exception);
void SignalHandler(int signal);
NSString* getAppInfo(void);@interface UncaughtExceptionHandler()
@property (assign, nonatomic) BOOL dismissed;
@end@implementation UncaughtExceptionHandler+ (void)installUncaughtExceptionHandler:(BOOL)install showAlert:(BOOL)showAlert {if (install && showAlert) {[[self alloc] alertView:showAlert];}NSSetUncaughtExceptionHandler(install ? HandleException : NULL);signal(SIGABRT, install ? SignalHandler : SIG_DFL);signal(SIGILL, install ? SignalHandler : SIG_DFL);signal(SIGSEGV, install ? SignalHandler : SIG_DFL);signal(SIGFPE, install ? SignalHandler : SIG_DFL);signal(SIGBUS, install ? SignalHandler : SIG_DFL);signal(SIGPIPE, install ? SignalHandler : SIG_DFL);
}- (void)alertView:(BOOL)show {showAlertView = show;
}+ (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;
}- (void)handleException:(NSException *)exception {[self validateAndSaveCriticalApplicationData:exception];if (!showAlertView) {return;}UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"出錯(cuò)啦"message:@"你可以嘗試?yán)^續(xù)操作,但是應(yīng)用可能無法正常運(yùn)行."delegate:selfcancelButtonTitle:@"退出"otherButtonTitles:@"繼續(xù)", nil];[alert show];CFRunLoopRef runLoop = CFRunLoopGetCurrent();CFArrayRef allModes = CFRunLoopCopyAllModes(runLoop);while (!self.dismissed) {for (NSString *mode in (__bridge NSArray *)allModes) {CFRunLoopRunInMode((CFStringRef)mode, 0.001, false);}}CFRelease(allModes);NSSetUncaughtExceptionHandler(NULL);signal(SIGABRT, SIG_DFL);signal(SIGILL, SIG_DFL);signal(SIGSEGV, SIG_DFL);signal(SIGFPE, SIG_DFL);signal(SIGBUS, SIG_DFL);signal(SIGPIPE, SIG_DFL);if ([[exception name] isEqual:UncaughtExceptionHandlerSignalExceptionName]) {kill(getpid(), [[[exception userInfo] objectForKey:UncaughtExceptionHandlerSignalKey] intValue]);} else {[exception raise];}
}- (void)alertView:(UIAlertView *)anAlertView clickedButtonAtIndex:(NSInteger)anIndex {if (anIndex == 0) {self.dismissed = YES;}
}- (void)validateAndSaveCriticalApplicationData:(NSException *)exception {NSString *exceptionInfo = [NSString stringWithFormat:@"\n--------Log Exception---------\nappInfo ? ? ? ? ? ? :\n%@\n\nexception name ? ? ?:%@\nexception reason ? ?:%@\nexception userInfo ?:%@\ncallStackSymbols ? ?:%@\n\n--------End Log Exception-----",getAppInfo(), exception.name, exception.reason, exception.userInfo ?: @"no user info", [exception callStackSymbols]];NSLog(@"%@", exceptionInfo);// 保存到文件等操作
}@endvoid HandleException(NSException *exception) {int32_t exceptionCount = OSAtomicIncrement32(&UncaughtExceptionCount);if (exceptionCount > UncaughtExceptionMaximum) {return;}NSArray *callStack = [exception callStackSymbols];NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:[exception userInfo]];[userInfo setObject:callStack forKey:UncaughtExceptionHandlerAddressesKey];[[[UncaughtExceptionHandler alloc] init]performSelectorOnMainThread:@selector(handleException:)withObject:[NSException exceptionWithName:[exception name] reason:[exception reason] userInfo:userInfo]waitUntilDone:YES];
}void SignalHandler(int signal) {int32_t exceptionCount = OSAtomicIncrement32(&UncaughtExceptionCount);if (exceptionCount > UncaughtExceptionMaximum) {return;}NSString* description = nil;switch (signal) {case SIGABRT:description = @"Signal SIGABRT was raised!";break;case SIGILL:description = @"Signal SIGILL was raised!";break;case SIGSEGV:description = @"Signal SIGSEGV was raised!";break;case SIGFPE:description = @"Signal SIGFPE was raised!";break;case SIGBUS:description = @"Signal SIGBUS was raised!";break;case SIGPIPE:description = @"Signal SIGPIPE was raised!";break;default:description = [NSString stringWithFormat:@"Signal %d was raised!", signal];}NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];NSArray *callStack = [UncaughtExceptionHandler backtrace];[userInfo setObject:callStack forKey:UncaughtExceptionHandlerAddressesKey];[userInfo setObject:[NSNumber numberWithInt:signal] forKey:UncaughtExceptionHandlerSignalKey];[[[UncaughtExceptionHandler alloc] init]performSelectorOnMainThread:@selector(handleException:)withObject:[NSException exceptionWithName:UncaughtExceptionHandlerSignalExceptionName reason:description userInfo:userInfo]waitUntilDone:YES];
}NSString* getAppInfo() {NSString *appInfo = [NSString stringWithFormat:@"App : %@ %@(%@)\nDevice : %@\nOS Version : %@ %@\n",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"],[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"],[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"],[UIDevice currentDevice].model,[UIDevice currentDevice].systemName,[UIDevice currentDevice].systemVersion];return appInfo;
}
在`didFinishLaunchingWithOptions`中調(diào)用`installUncaughtExceptionHandler`:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {[UncaughtExceptionHandler installUncaughtExceptionHandler:YES showAlert:YES];return YES;
}
二、處理Signal
在Xcode中測試Signal類型崩潰時(shí),需在調(diào)試控制臺輸入以下命令,以允許Signal回調(diào)進(jìn)入處理函數(shù):
pro hand -p true -s false SIGABRT
三、測試代碼
- (void)viewDidLoad {[super viewDidLoad];[self exceptionHandlerTest1];// [self exceptionHandlerTest2];// [self exceptionHandlerTest3];
}/// 異常處理測試1
-(void)exceptionHandlerTest1{NSArray *array= @[@"tom",@"xxx",@"ooo"];[array objectAtIndex:5];
}/// 異常處理測試2
-(void)exceptionHandlerTest2{[self performSelector:@selector(string) withObject:nil afterDelay:2.0];
}/// 異常處理測試3
-(void)exceptionHandlerTest3{int list[2]={1,2};int *p = list;free(p);p[1] = 5;
}