1

当用户在 iPhone 上杀死应用程序时,有没有办法执行一些最后的操作?

在 UIApplicationDelegate 中有 applicationWillTerminate: 但据我了解,不能保证在应用程序终止时调用它。还有其他方法吗?

4

4 回答 4

3

你不能依赖applicationWillTerminate被召唤。从文档中:

对于不支持后台执行或链接到 iOS 3.x 或更早版本的应用程序,当用户退出应用程序时始终调用此方法。对于支持后台执行的应用程序,当用户退出应用程序时通常不会调用此方法,因为在这种情况下应用程序只是移动到后台。但是,在应用程序在后台运行(未挂起)并且系统出于某种原因需要终止它的情况下,可能会调用此方法。

保存任何状态的正确位置是应用程序进入后台时。一旦发生这种情况,就无法知道应用程序是否会返回前台,或者它是否会被杀死然后从头开始。

于 2013-03-07T00:10:57.337 回答
0

All methods concerning your app state are in your AppDelegate when you use one of the project templates.

Put the code in the applicationWillResignActive: method. It will get called if your app goes to an inactive state (terminating or no).

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
于 2013-03-06T23:59:51.173 回答
0

保存状态的“正确”位置在 -applicationDidEnterBackground:-applicationWillTerminate:。不用担心双重储蓄;通常只调用其中一个(IME,-applicationWillTerminate:当您的应用在后台被杀死时不会调用)。

警告-applicationDidEnterBackground:保证会被调用,因为它是您的应用程序进入后台后调用的(因此有资格在不通知的情况下被杀死!)。如果您的应用程序在后台运行时设备内存不足,它可能会被杀死。避免这种情况的最好方法是首先不要使用太多内存。

可以使用 -applicationWillResignActive:,但我不建议这样做:应用程序变得非常频繁地处于非活动状态。一个明显的是系统对话框(位置/隐私提示、Wi-Fi、显示为警报、警报的通知)、TWTweetSheet,我怀疑 MFMailComposeViewController、MFMessageComposeViewController、通知中心、应用程序切换栏(例如,更改曲目/启用方向锁定)。

于 2013-03-07T00:43:42.977 回答
-1

您可以在 appdelegate 中使用 applicationWillResignActive 方法,或者您可以执行以下操作,如果您想保存内容,但由于某种原因,您不想在 app 委托中执行此操作:

- (void) viewDidLoad/init { 
    [[NSNotificationCenter defaultCenter]
        addObserver:self
        selector:@selector(myApplicationWillResign)
        name:UIApplicationWillResignActiveNotification 
        object:NULL];
}

- (void) myApplicationWillResign {
    NSLog(@"About to die, perform last actions");
}
于 2013-03-07T00:09:54.380 回答