崩溃

异常处理

  • 抛出异常。此时程序会强制停止
    • @throw [NSException exceptionWithName:@"牛逼的错误" reason:@"方法找不到" userInfo:nil];
    • [NSException raise:@"牛逼的错误" format:@"%s",__func__];
  • 拦截异常
@try {
        @[][0];
    } @catch (NSException *exception) {
        NSLog(@"代码有异常-%@",exception);
    } @finally {
        NSLog(@"finally");
    }
  • 如果try里面的代码有错误,会执行catch,然后执行finally;如果try没有错误,执行完try,直接执行finally

崩溃统计分析

  • 方法一。在main函数中拦截崩溃。不过一般不这么干。
int main(int argc, char * argv[]) {
    @try {
        @autoreleasepool {
            return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
        }
    } @catch (NSException *exception) {
    //存放崩溃信息到本地
        NSString *file = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)objectAtIndex:0];
        NSString *fileName = [file stringByAppendingPathComponent:@"exception"];
        [[exception callStackSymbols] writeToFile:fileName atomically:YES];
    } @finally {

    }
}
  • 方法二。在appDelegate中拦截异常。在崩溃之前拦截。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //这句是关键代码
    NSSetUncaughtExceptionHandler(handleException);
    return YES;
}
//函数名随意
void handleException(NSException *exception){
//崩溃信息文件存放位置
    NSString *file = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    NSLog(@"file--%@",file);
    NSString *fileName = [file stringByAppendingPathComponent:@"exception"];
  //崩溃信息字典
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    info[@"callStack"] = [exception callStackSymbols];//调用栈信息(错误来源于哪个方法)
    info[@"name"] = [exception name];//异常名字
    info[@"reason"] = [exception reason]; //异常描述(报错理由)
    [info writeToFile:fileName atomically:YES];
}
  • 方法三。第三方
    • 友盟
    • Flurry
    • Crashlytics

弹出提醒的方法

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSSetUncaughtExceptionHandler(handleException);
    return YES;
}

void handleException(NSException *exception){
    [[UIApplication sharedApplication].delegate performSelector:@selector(handle)];
}

-(void)handle{
    UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"哈哈" message:@"我是闪退前的挣扎" delegate:self cancelButtonTitle:@"好的" otherButtonTitles: nil];
    [view show]; 
    //重新启动runloop。这句是关键代码
    [[NSRunLoop currentRunLoop]addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop]run];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"点击了好的");
    exit(0);
}

你可能感兴趣的:(崩溃)