iOS 捕获程序崩溃日志

iOS开发中遇到程序崩溃是很正常的事情,如何在程序崩溃时捕获到异常信息并通知开发者?

下面就介绍如何在iOS中实现:

1. 在程序启动时加上一个异常捕获监听,用来处理程序崩溃时的回调动作

NSSetUncaughtExceptionHandler (&UncaughtExceptionHandler);

官方文档介绍:Sets the top-level error-handling function where you can perform last-minute logging before the program terminates.
UncaughtExceptionHandler是一个函数指针,该函数需要我们实现,可以取自己想要的名字。当程序发生异常崩溃时,该函数会得到调用,这跟C,C++中的回调函数的概念是一样的。

2. 实现自己的处理函数

void UncaughtExceptionHandler(NSException *exception) {
    NSArray *arr = [exception callStackSymbols];//得到当前调用栈信息
    NSString *reason = [exception reason];//非常重要,就是崩溃的原因
    NSString *name = [exception name];//异常类型
   
    NSLog(@"exception type : %@ \n crash reason : %@ \n call stack info : %@", name, reason, arr);
}

以上代码很简单,但是带来的作用是非常大的。

posted @ 2015-03-24 18:29  90后码农  阅读(389)  评论(0编辑  收藏  举报