一.设置NSZombieEnabled
使用NSZombieEnabled功能,当代码中访问已经释放了内存的地方,会给你下面这样的提示,而不仅仅是EXEC_BAD_ACCESS:
2008-10-0318:10:39.933HelloWorld[1026:20b] *** -[GSFont ascender]: message sent to deallocated instance0x126550
如果要查看上面地址的分配情况
开启MallocStackLogging(Xcode4勾选下MallocStackLogging就行)
出错时shell malloc_history pid address
另:有时候可以重载respondsToSelector可以帮你找到程序崩溃时最后执行的函数,然后排查.
二.添加全局断点
Xcode4可以很方便的添加全局的异常断点
三.中断和未捕获异常
1.未拦截信号来源:内核,其他程序,本身.
常见的两个信号:
1).EXC_BAD_ACCESS 试图访问非法内存,导致SIGBUS或者SIGSEGV信号<wbr></wbr>
2).未能拦截obj_exception_throw导致的SIGABRT信号.
2.方法
1).使用NSUncaughtionHandler安装一个handler拦截未拦截异常
2).使用signal函数安装一个handler拦截BSD信号.(SIGKILL[kill -9]和SIGSTOP[Control+z]无法拦截)
两个c函数
voidSignalHandler(intsignal) { //中断信号 } voiduncaughtExceptionHandler<wbr>(NSException *exception) { <span style="word-wrap:normal; word-break:normal; color:rgb(0,128,0)">//</span><span style="word-wrap:normal; word-break:normal; color:rgb(0,128,0)">未捕获异常</span><span style="word-wrap:normal; word-break:normal; color:rgb(0,128,0)"> </span>}</wbr>
安装(与全局异常断点冲突,当有这样的断点是,下面拦截函数失效)
voidInstallUncaughtException<wbr>Handler()
{
NSSetUncaughtExceptionHa<wbr>ndler(&uncaughtExceptionHandler<wbr>);
signal(SIGABRT, SignalHandler);
signal(SIGILL, SignalHandler);
signal(SIGSEGV, SignalHandler);
signal(SIGFPE, SignalHandler);
signal(SIGBUS, SignalHandler);
signal(SIGPIPE, SignalHandler);
}</wbr></wbr></wbr>
3.具体实例
1.http://cocoawithlove.com/2010/05/handling-unhandled-exceptions-and.html
重点在于尝试继续运行程序
告诉用户那些因为这些未拦截的异常和信号导致的崩溃,或者自己记录,甚至可以避开这样导致的崩溃.不过,如果多个信号拦截了,这可能失效.
非常推荐看看这篇文章
2.http://parveenkaler.com/2010/08/11/crashkit-helping-your-iphone-apps-suck-less/
重点在于记录异常(之后返回主线程)
- (void)pumpRunLoop
{
self.finishPump = NO;
CFRunLoopRef runLoop = CFRunLoopGetCurrent();
CFArrayRef runLoopModesRef = CFRunLoopCopyAllModes(runLoop);
NSArray * runLoopModes = (NSArray*)runLoopModesRef;
while(self.finishPump == NO)
{
for(NSString *modeinrunLoopModes){
CFStringRef modeRef = (CFStringRef)mode;
CFRunLoopRunInMode(modeRef,1.0f/120.0f,false);//Pump the loop at 120 FPS
}
}
CFRelease(runLoopModesRef);
}