我有一个视图控制器,它使用NSTimer
来执行一些代码。
检测应用程序何时转到后台的最佳方法是什么,以便我可以暂停计时器?
发布于 2012-01-26 09:04:02
您可以让任何对应用程序何时进入后台接收通知感兴趣的类。这是将这些类与AppDelegate耦合的一个很好的替代方案。
在初始化所述类时:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillTerminate:) name:UIApplicationWillTerminateNotification object:nil];
响应通知
-(void)appWillResignActive:(NSNotification*)note
{
}
-(void)appWillTerminate:(NSNotification*)note
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];
}
发布于 2012-01-26 07:19:25
在您的应用程序AppDelegate上,iOS将调用(void)applicationDidEnterBackground:(UIApplication *)application
方法。你可以把你的定时器停在那里。
发布于 2016-07-07 23:03:32
对于那些希望在Swift中做到这一点的人:
在init
上
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplicationWillResignActiveNotification, object: nil)
在deinit
上
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil)
响应通知:
dynamic private func applicationWillResignActive() {
// Do things here
}
Apple鼓励我们在Swift中尽可能避免动态分派和Objective-C选择器,但这仍然是最方便的方法。
https://stackoverflow.com/questions/9011868
复制相似问题