IOS应用从容地崩溃

来源:互联网 发布:保温厚度计算软件 编辑:程序博客网 时间:2024/04/29 10:05

 IOS的崩溃如果不做处理是闪退的。虽然我不赞成IOS应用有崩溃的现象,但是难免遗漏导致崩溃。或者一些特殊的应用 要在完全退出后在进行测试。这样联机调试就不能实现了。所以可以用以下方法来处理。如下

IOS SDK中提供了一个现成的函数 NSSetUncaughtExceptionHandler 用来做异常处理,但功能非常有限,而引起崩溃的大多数原因如:内存访问错误,重复释放等错误就无能为力了,因为这种错误它抛出的是Signal,所以必须要专门做Signal处理。在didFinishLaunchingWithOptions 中,加入代码如下:(以下代码有高手所写   如是原作者可联系本人  478043385@qq.com  或留言)

Source code    

signal(SIGABRT, MySignalHandler);

signal(SIGILL, MySignalHandler);

signal(SIGSEGV, MySignalHandler);

signal(SIGFPE, MySignalHandler);

signal(SIGBUS, MySignalHandler);

signal(SIGPIPE, MySignalHandler);

回调函数MySignalHandler的定义如下:

void MySignalHandler(int signal)

{

int32_t exceptionCount = OSAtomicIncrement32(&UncaughtExceptionCount);

if (exceptionCount > UncaughtExceptionMaximum)

{

return;

}

NSMutableDictionary *userInfo =

[NSMutableDictionary

dictionaryWithObject:[NSNumber numberWithInt:signal]

forKey:UncaughtExceptionHandlerSignalKey];

NSArray *callStack = [UncaughtExceptionHandler backtrace];

[userInfo

setObject:callStack

forKey:UncaughtExceptionHandlerAddressesKey];

[[[[UncaughtExceptionHandler alloc] init] autorelease]

performSelectorOnMainThread:@selector(handleException:)

withObject:

[NSException

exceptionWithName:UncaughtExceptionHandlerSignalExceptionName

reason:

[NSString stringWithFormat:

NSLocalizedString(@"Signal %d was raised.\n"

@"%@", nil),

signal, getAppInfo()]

userInfo:

[NSDictionary

dictionaryWithObject:[NSNumber numberWithInt:signal]

forKey:UncaughtExceptionHandlerSignalKey]]

waitUntilDone:YES];

}

这段代码将会在崩溃时弹出一个对话框,我们还可以让它显示出设备信息,如下:

NSString* getAppInfo()

{

NSString *appInfo = [NSString stringWithFormat:@"App : %@ %@(%@)\nDevice : %@\nOS Version : %@ %@\nUDID : %@\n",

[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"],

[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"],

[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"],

[UIDevice currentDevice].model,

[UIDevice currentDevice].systemName,

[UIDevice currentDevice].systemVersion,

[UIDevice currentDevice].uniqueIdentifier];

NSLog(@"Crash!!!! %@", appInfo);

return appInfo;

}

 

 

原创粉丝点击