我有一个观察员,检查应用程序何时变为活动状态并调用applicationDidBecomeActive
。当我删除该代码时,没有任何崩溃,但我需要该代码。
我在addActiveObserver
中拨打ViewDidAppear
,在removeActiveObserver
中拨打ViewDidDisappear
,但是当我在每个网站上设置断点时,只有ViewDidAppear
被点击。
当我再次点击主页按钮然后点击应用程序时,我发生了以下崩溃:
applicationDidBecomeActive:]: unrecognized selector sent to instance
viewDidAppear
/ viewDidDisappear
:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
addActiveObserver()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
removeActiveObserver()
}
addActiveObserver
/ removeActiveObserver
func addActiveObserver() {
NotificationCenter.default.addObserver(
self,
selector: #selector(UIApplicationDelegate.applicationDidBecomeActive(_:)),
name: NSNotification.Name.UIApplicationDidBecomeActive,
object: nil)
}
func removeActiveObserver() {
NotificationCenter.default.removeObserver(self,
name:NSNotification.Name.UIApplicationDidBecomeActive,
object:nil)
}
applicationDidBecomeActive
:
func applicationDidBecomeActive(_ notification: Notification) {
// Do work
}
答案 0 :(得分:2)
您不需要选择器中的UIApplicationDelegate
部分,因为它指的是应用程序的常规委托中的函数而不是您所在的自定义类中的函数有。你应该删除它。
NotificationCenter.default.addObserver(
self,
selector: #selector(applicationDidBecomeActive(_:)),
name: .UIApplicationDidBecomeActive,
object: nil)