更好的使用UIApplicationWillResignActive
和UIApplicationDidBecomeActive
,因爲它們捕獲了「頂部矩形捕獲和釋放事件」。 我會建議使用這根類:
class VBase: UIViewController {
fileprivate var listenersActivated = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
onStart()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
onStop()
removeListeners()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
onStop()
removeListeners()
}
internal func iniListeners() {
if (!listenersActivated) {
NotificationCenter.default.addObserver(self, selector: #selector(onStop), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(onStart), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
listenersActivated = true
} else {
}
}
internal func removeListeners() {
NotificationCenter.default.removeObserver(self)
listenersActivated = false
}
internal func onStop() {
}
internal func onStart() {
iniListeners()
}
}
覆蓋onStop()
和onStart()
裏面孩子的捕獲所有視圖出現/消失
也就是說,
class SomeViewController: VBase {
...
override func onStart() {
super.onStart()
someFunctionToInitialize()
}
override func onStop() {
super.onStop()
stopTimer()
someFunctionToDesctruction()
}
}
嘗試使用「applicationWillTerminate」方法。:-) – 2012-04-25 22:35:09
「applicationWillTerminate」方法不存在。但是,子類可以註冊UIApplicationWillTerminateNotification,然後執行自己的清理或關閉。 – 2012-05-18 15:02:47