您的位置:首页 > 移动开发 > IOS开发

IOS崩溃异常的处理

2015-11-18 15:11 357 查看
IOS崩溃异常的处理

会闪退的异常种类有:数组越界、空引用、引用未定义方法、内存空间不足等等。以下是对APP进行异常监听的处理方法:

1、在AppDelegate的didFinishLaunchingWithOptions方法中添加异常捕获监听

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

//加上异常捕获监听,用来处理程序崩溃时的回调动作,UncaughtExceptionHandler是一个函数指针,该函数需要我们实现,可以取自己想要的名字。当程序发生异常崩溃时,该函数会得到调用

NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);



2、在AppDelegate.m中实现UncaughtExceptionHandler方法,此处处理异常有两种方法,第一种是保存在本地文件(下次启动时可查看),第二种是将异常崩溃信息发送至开发者邮箱

#pragma mark - 崩溃异常处理方法

void UncaughtExceptionHandler( NSException *exception){

NSArray *arr=[exception callStackSymbols];//得到当前调用栈信息

NSString *reason=[exception reason];//获取崩溃的原因

NSString *name=[exception name];//异常名称

NSString *exceptionInfo=[NSString stringWithFormat:@"Exception type:%@ \n crash reason:%@ \n call stack info:%@",name,reason,arr];

NSLog(@"崩溃异常打印:%@",exceptionInfo);

// //异常处理方法一:将异常保存在本地文件中,下次启动的时候,可以查看

// NSMutableArray *tmpArr=[NSMutableArray arrayWithArray:arr];

// [tmpArr insertObject:reason atIndex:0];

// [exceptionInfo writeToFile:[NSString stringWithFormat:@"%@/Documents/error.log",NSHomeDirectory()] atomically:YES encoding:NSUTF8StringEncoding error:nil];

//异常处理方法二:将异常崩溃信息发送至开发者邮箱

NSMutableString *mailUrl=[NSMutableString string];

[mailUrl appendString:@"mailto:593206782@qq.com"];

[mailUrl appendString:@"?subject=程序异常崩溃,请配合发送异常报告,谢谢合作!"];

[mailUrl appendFormat:@"&body=%@",exceptionInfo];

//打开地址

NSString *mailPath=[mailUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailPath]];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: