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 關注
- 469 瀏覽
添加回答
舉報