【发布时间】:2017-02-21 23:12:11
【问题描述】:
当用户在 iPhone 上终止应用程序时,有没有办法执行一些最后的操作?
在 UIApplicationDelegate 中有 applicationWillTerminate: 但据我了解,不能保证在应用程序终止时调用它。还有其他方法吗?
【问题讨论】:
-
它会被调用,但用户退出不一定是终止。 willResignActive 会告诉你退出(终止与否)。
当用户在 iPhone 上终止应用程序时,有没有办法执行一些最后的操作?
在 UIApplicationDelegate 中有 applicationWillTerminate: 但据我了解,不能保证在应用程序终止时调用它。还有其他方法吗?
【问题讨论】:
你不能依赖 applicationWillTerminate 被调用。来自文档:
对于不支持后台执行或链接到 iOS 3.x 或更早版本的应用程序,当用户退出应用程序时始终调用此方法。对于支持后台执行的应用程序,当用户退出应用程序时通常不会调用此方法,因为在这种情况下应用程序只是移动到后台。但是,在应用程序在后台运行(未挂起)并且系统出于某种原因需要终止它的情况下,可能会调用此方法。
保存任何状态的适当位置是应用程序进入后台时。一旦发生这种情况,就无法知道应用程序是否会返回前台,或者它是否会被杀死然后从头开始。
【讨论】:
-applicationWillTerminate: 也将在 iPhone 3G 上调用(支持它很棘手,但并非不可能),并且文档还说“在应用程序运行在后台(未挂起),系统出于某种原因需要终止它”。为避免在添加后台任务/等时被咬,最好两者都支持。
当您使用其中一个项目模板时,所有与您的应用状态相关的方法都在您的 AppDelegate 中。
将代码放在applicationWillResignActive: 方法中。如果您的应用进入非活动状态(终止或否),它将被调用。
- (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.
}
【讨论】:
保存状态的“正确”位置是-applicationDidEnterBackground: 和-applicationWillTerminate:。不用担心双重储蓄;通常只调用其中一个(IME,-applicationWillTerminate: 在您的应用在后台被杀死时不会被调用)。
警告:-applicationDidEnterBackground: 不保证会被调用,因为它是在您的应用进入后台后调用的(因此变成有资格在没有通知的情况下被杀!)。如果您的应用程序在后台运行时设备内存不足,它可能会被杀死。避免这种情况的最佳方法是一开始就不要使用太多内存。
你可以使用
-applicationWillResignActive:,但我不建议这样做:应用程序变得非常频繁地处于非活动状态。一个明显的是系统对话框(位置/隐私提示、Wi-Fi、显示为警报、警报的通知)、TWTweetSheet,我怀疑 MFMailComposeViewController、MFMessageComposeViewController、通知中心、应用程序切换栏(例如,更改曲目/启用方向锁定)。
【讨论】:
您可以在 appdelegate 中使用 applicationWillResignActive 方法,或者您可以执行以下操作,如果您想保存内容,但由于某种原因,您不想在 appdelegate 中执行此操作:
- (void) viewDidLoad/init {
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(myApplicationWillResign)
name:UIApplicationWillResignActiveNotification
object:NULL];
}
- (void) myApplicationWillResign {
NSLog(@"About to die, perform last actions");
}
【讨论】: