2010-12-03 68 views
2

我正在嘗試將Matt Gallagher的全局異常處理程序添加到我的其中一個項目中。運行位於他的榜樣項目:iOS - UncaughtExceptions全局異常處理程序不允許應用程序退出

http://cocoawithlove.com/2010/05/handling-unhandled-exceptions-and.html

我碰上,我按下退出的問題和應用程序不退出。它只是讓我回到應用程序。我嘗試用kill()調用殺死應用程序,但無法讓應用程序退出。

從alertview的回調似乎只處理繼續的情況下,並沒有處理強迫應用程序退出。

- (void)alertView:(UIAlertView *)anAlertView clickedButtonAtIndex:(NSInteger)anIndex 
{ 
    if (anIndex == 0) 
    { 
     dismissed = YES; 
    } 
} 

我知道的應用程序,根據其性質不能放棄自己,但在這種情況下,如果應用程序崩潰,我想用戶按下退出鍵,並有應用程序退出。

謝謝!

回答

5

蘋果不相信退出按鈕。但是你可以拋出另一個你不會導致應用崩潰的異常,但是如果你的應用崩潰了,那麼它將不會被批准。

我認爲最接近你可以通過在你的info.plist中將UIApplicationExitsOnSuspend設置爲true來禁用背景,然後按下home按鈕將退出你的應用程序。在這種情況下,您可以使退出按鈕成爲任何其他應用程序的鏈接。

將if語句更改爲始終引發異常應該會導致應用程序崩潰,因此它將退出。

- (void)handleException:(NSException *)exception 
{ 
    [self validateAndSaveCriticalApplicationData]; 

    UIAlertView *alert = 
     [[[UIAlertView alloc] 
      initWithTitle:NSLocalizedString(@"Unhandled exception", nil) 
      message:[NSString stringWithFormat:NSLocalizedString(
       @"You can try to continue but the application may be unstable.\n\n" 
       @"Debug details follow:\n%@\n%@", nil), 
       [exception reason], 
       [[exception userInfo] objectForKey:UncaughtExceptionHandlerAddressesKey]] 
      delegate:self 
      cancelButtonTitle:NSLocalizedString(@"Quit", nil) 
      otherButtonTitles:NSLocalizedString(@"Continue", nil), nil] 
     autorelease]; 
    [alert show]; 

    CFRunLoopRef runLoop = CFRunLoopGetCurrent(); 
    CFArrayRef allModes = CFRunLoopCopyAllModes(runLoop); 

    while (!dismissed) 
    { 
     for (NSString *mode in (NSArray *)allModes) 
     { 
      CFRunLoopRunInMode((CFStringRef)mode, 0.001, false); 
     } 
    } 

    CFRelease(allModes); 

    NSSetUncaughtExceptionHandler(NULL); 
    signal(SIGABRT, SIG_DFL); 
    signal(SIGILL, SIG_DFL); 
    signal(SIGSEGV, SIG_DFL); 
    signal(SIGFPE, SIG_DFL); 
    signal(SIGBUS, SIG_DFL); 
    signal(SIGPIPE, SIG_DFL); 

    [exception raise]; 
} 
+1

如果您絕對需要強制關閉應用程序,您可以調用`abort()`。 – 2010-12-03 22:51:27