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


当前回答

您是否尝试过exit(0)?

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

其他回答

苹果说:

警告:不要调用exit函数。调用exit的应用程序将在用户看来已经崩溃,而不是执行优雅的终止并动画返回主屏幕。”

我认为这是一个错误的假设。如果用户点击退出按钮,出现类似“应用程序现在将退出”这样的消息,它似乎没有崩溃。苹果应该提供退出应用程序的有效方法(而不是exit(0))。

在application-info上添加UIApplicationExitsOnSuspend属性。请承认是真的。

Exit(0)在用户面前显示为崩溃,因此向用户显示确认消息。确认后暂停(home键按程序),等待2秒,应用程序将进入后台动画,然后退出用户视图

-(IBAction)doExit
{
    //show confirmation message to user
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Confirmation"
                                                 message:@"Do you want to exit?"
                                                delegate:self
                                       cancelButtonTitle:@"Cancel"
                                       otherButtonTitles:@"OK", nil];
    [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
        exit(0);
    }
}

我们不能使用exit(0), abort()函数退出应用程序,因为苹果强烈反对使用这些函数。不过,您可以将此函数用于开发或测试目的。

如果在开发或测试期间,有必要终止您的 建议使用应用程序、中止函数或断言宏

请找到这个苹果问答线程以获得更多信息。

由于使用此功能创建印象,应用程序正在崩溃。所以我得到了一些建议,比如我们可以显示警报与终止消息意识到用户关闭应用程序,由于某些功能不可用。

但是iOS人机界面启动和停止应用指南,建议永远不要使用退出或关闭按钮来终止应用。而不是他们建议展示适当的信息来解释情况。

iOS应用永远不会显示关闭或退出选项。人们不再使用 当他们切换到另一个应用程序,返回主屏幕,或放 他们的设备处于睡眠模式。 永远不要以编程方式退出iOS应用程序。人们倾向于这样解释 作为一个崩溃。如果有什么东西阻止你的应用程序运行 有意的,你需要告诉用户情况和解释什么 他们可以做些什么。

点击这里查看问答:https://developer.apple.com/library/content/qa/qa1561/_index.html

Q: How do I programmatically quit my iOS application? There is no API provided for gracefully terminating an iOS application. In iOS, the user presses the Home button to close applications. Should your application have conditions in which it cannot provide its intended function, the recommended approach is to display an alert for the user that indicates the nature of the problem and possible actions the user could take — turning on WiFi, enabling Location Services, etc. Allow the user to terminate the application at their own discretion. WARNING: Do not call the exit function. Applications calling exit will appear to the user to have crashed, rather than performing a graceful termination and animating back to the Home screen. Additionally, data may not be saved, because -applicationWillTerminate: and similar UIApplicationDelegate methods will not be invoked if you call exit. If during development or testing it is necessary to terminate your application, the abort function, or assert macro is recommended