NSNotificationCenter中addObserver和removeObserver成对出现的问题

把下边的code放在storyboard中执行(灵活的注释一些行),可以看到一下效果:
1.多次addObserver,会导致对应的方法执行多次;
2.多次addObserver,一次remove,虽然不能把多有notification移除掉,但是只要所在容器类析构,就会移除掉其所有的notification

import UIKit
let customNotification: String = "customNotification"
class Manager {
    
    deinit {
        print("deinit")
        NSNotificationCenter.defaultCenter().removeObserver(self, name: customNotification, object: nil)
    }
    
    init() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Manager.notificationHandler(_:)), name: customNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Manager.notificationHandler(_:)), name: customNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Manager.notificationHandler(_:)), name: customNotification, object: nil)
    }
    
    func postNotification() {
        NSNotificationCenter.defaultCenter().postNotificationName(customNotification, object: nil, userInfo: nil)
    }
    
    @objc func notificationHandler(notification: NSNotification) {
        print("notificationHandler")
    }
}

var manager: Manager? = Manager()
manager?.postNotification()
manager = nil

NSNotificationCenter.defaultCenter().postNotificationName(customNotification, object: nil, userInfo: nil)

你可能感兴趣的:(NSNotificationCenter中addObserver和removeObserver成对出现的问题)