好吧,这是相当灾难性的。
你们必须注意事件注册/注销,因为您可能会导致内存泄漏。
为了使一切正常,您需要设置一个知道注册状态的标志:您是否已登录后台事件。请注意,当用户看到视图控制器(如果他来自其他用户)或者如果他从主屏幕来到您的视图控制器时,您需要注册事件。
当您将视图控制器留给另一个视图控制器时,您还需要取消注册。
简而言之:
斯威夫特 4:
private var registeredToBackgroundEvents = false
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
registerToBackFromBackground()
}
/// register to back from backround event
private func registerToBackFromBackground() {
if(!registeredToBackgroundEvents) {
NotificationCenter.default.addObserver(self,
selector: #selector(viewDidBecomeActive),
name: UIApplication.didBecomeActiveNotification, object: nil)
registeredToBackgroundEvents = true
}
}
/// unregister from back from backround event
private func unregisterFromBackFromBackground() {
if(registeredToBackgroundEvents) {
NotificationCenter.default.removeObserver(self,
name: UIApplication.didBecomeActiveNotification, object: nil)
registeredToBackgroundEvents = false
}
}
@objc func viewDidBecomeActive(){
logicManager.onBackFromStandby()
}
override func viewWillDisappear(_ animated: Bool) {
unregisterFromBackFromBackground()
}