3 回答

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊
當(dāng)應(yīng)用程序進(jìn)入后臺(tái)時(shí),您可以對(duì)任何感興趣的類(lèi)進(jìn)行接收通知。這是將這些類(lèi)與AppDelegate耦合的不錯(cuò)選擇。
在初始化所述類(lèi)時(shí):
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillTerminate:) name:UIApplicationWillTerminateNotification object:nil];
回應(yīng)通知
-(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貢獻(xiàn)1891條經(jīng)驗(yàn) 獲得超3個(gè)贊
對(duì)于那些希望在Swift中做到這一點(diǎn)的人:
開(kāi)init:
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplicationWillResignActiveNotification, object: nil)
開(kāi)deinit:
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil)
響應(yīng)通知:
dynamic private func applicationWillResignActive() {
// Do things here
}
Apple鼓勵(lì)我們?cè)赟wift中盡可能避免使用動(dòng)態(tài)調(diào)度和Objective-C選擇器,但這仍然是最方便的方法。
- 3 回答
- 0 關(guān)注
- 690 瀏覽
添加回答
舉報(bào)