美文网首页
NSNotificationCenter中addObserver

NSNotificationCenter中addObserver

作者: 努力奔跑的____ | 来源:发表于2016-12-08 10:35 被阅读0次

    把下边的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

          本文链接:https://www.haomeiwen.com/subject/bbajmttx.html