检测应用程序何时进入我的视图背景的最佳方法是什么?

我有一个视图控制器,它使用NSTimer来执行一些代码。

检测应用何时进入后台以便暂停计时器的最佳方法是什么?


叮当猫咪
浏览 411回答 3
3回答

浮云间

当应用程序进入后台时,您可以对任何感兴趣的类进行接收通知。这是将这些类与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];}

慕后森

对于那些希望在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选择器,但这仍然是最方便的方法。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

iOS