从其他ViewController移除NSNotificationObserver

时间:2018-08-05 19:35:10

标签: swift nsnotificationcenter nsnotifications

我有一个观察者,我这样注册一堂课:

class ViewControllerA: UIViewController {

//create shared class reference
var sharedClassReference_A = SharedClass()


//initialize Notification Observer and store observer reference in sharedClass
override func viewDidLoad() {
    super.viewDidLoad()

    var observerHandler: Any? = nil

    observerHandler = NotificationCenter.default.addObserver(self, selector: #selector(ViewControllerA.appDidTerminate(_:)), name: .UIApplicationWillTerminate, object: nil)

    self.sharedClassReference_A.sharedHandler = observerHandler

}

//perform some action when a notification is received
@objc func appDidTerminate(_ notification: NSNotification) {

    //perform some action

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "segueA_X" {
        let destinationController = segue.destination as! ViewControllerX
       destinationController.sharedClassReference_X = self.sharedClassReference_A
    }
}

}

我在共享类中存储了对观察者的引用:

class SharedClass {

var sharedHandler: Any? = nil

}

一旦到达其他视图控制器,我便尝试删除观察者:

class ViewControllerX: UIViewController {

var sharedClassReference_X = SharedClass()

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    //Attempt to remove observer registered in ViewControllerA
    if let observerHandler = self.sharedClassReference_X.sharedHandler {
         NotificationCenter.default.removeObserver(observerHandler)
    }
}

}

我知道使用这种方法删除观察者失败了,因为在释放ViewControllerX之后调用了观察者。

我的问题是:如何在一个类(ViewControllerA)中成功初始化观察者,并在以后在另一个类(ViewControllerX)中将其删除?

1 个答案:

答案 0 :(得分:0)

我认为最好遵循以下一般准则:根据您的情况分别在viewDidLoad / viewWillAppear内设置观察者,并在deinit / viewDidDisappear内移除观察者,如下这个

NotificationCenter.default.addObserver(self, selector: #selector(ViewControllerA.appDidTerminate(_:)), name: .UIApplicationWillTerminate, object: nil)

返回无效

//

class ViewControllerX: UIViewController { 
   var aRef:ViewControllerA!
}

在prepareForSegue

destinationController.aRef = self

然后使用

NotificationCenter.default.removeObserver(aRef, name: NSNotification.Name.UIApplicationWillTerminate, object: nil)