我正在编程一个iPhone应用程序,我需要强制它退出由于某些用户操作。在清理应用程序分配的内存后,调用什么方法来终止应用程序?


当前回答

在iPhone上,没有退出应用的概念。导致应用退出的唯一操作是触摸手机上的Home键,而这不是开发者可以访问的。

根据苹果公司的说法,你的应用程序不应该自行终止。因为用户没有点击Home键,所以任何返回到Home屏幕的操作都会给用户留下应用程序崩溃的印象。这是令人困惑的,不规范的行为,应该避免。

其他回答

Swift 4.2(或更老版本)

库称为达尔文可以使用。

import Darwin

exit(0) // Here you go

注意:在iOS应用程序中不建议这样做。

这样做会得到崩溃日志。

您是否尝试过exit(0)?

或者,[[NSThread主线程]退出],虽然我没有尝试,这似乎是更合适的解决方案。

除了上面的,很好,答案我只想补充一下,想想清理你的记忆。

应用程序退出后,iPhone操作系统将自动清理应用程序遗留的所有内容,因此手动释放所有内存只会增加应用程序退出所需的时间。

- (IBAction)logOutButton:(id)sender
{
   //show confirmation message to user
   CustomAlert* alert = [[CustomAlert alloc] initWithTitle:@"Confirmation" message:@"Do you want  to exit?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
   alert.style = AlertStyleWhite;
   [alert setFontName:@"Helvetica" fontColor:[UIColor blackColor] fontShadowColor:[UIColor clearColor]];
   [alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{

   if (buttonIndex != 0)  // 0 == the cancel button
   {
      //home button press programmatically
      UIApplication *app = [UIApplication sharedApplication];
      [app performSelector:@selector(suspend)];
      //wait 2 seconds while app is going background
      [NSThread sleepForTimeInterval:2.0];
      //exit app when app is in background
      NSLog(@"exit(0)");
      exit(0);
  }
}
[[UIApplication sharedApplication] terminateWithSuccess];

它工作正常,自动调用

- (void)applicationWillTerminateUIApplication *)application delegate.

要删除编译时警告,请添加以下代码

@interface UIApplication(MyExtras)
  - (void)terminateWithSuccess;
@end