3 回答
TA贡献1829条经验 获得超4个赞
当应用程序进入后台时,您可以对任何感兴趣的类进行接收通知。这是将这些类与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];
}
TA贡献1802条经验 获得超5个赞
对于那些希望在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选择器,但这仍然是最方便的方法。
- 3 回答
- 0 关注
- 441 浏览
添加回答
举报