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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • http://potter528.bj.bdysite.com最近在做平板的过程中,发现了一些很不规范的代码。偶然...
    Bug集阅读 728评论 0 0
  • 1.自定义控件 a.继承某个控件 b.重写initWithFrame方法可以设置一些它的属性 c.在layouts...
    圍繞的城阅读 3,515评论 2 4
  • 原文出处: http://www.androidchina.net/6174.html Notification在...
    木木00阅读 12,399评论 3 32
  • 闲来无事,翻起一本本厚实的影集,那里面有我的青春,也有很多美好的回忆。 人生的第一张照片是和妹妹的合影,那时我七岁...
    简儿的十年阅读 356评论 33 32
  • 前言: 刚更新了iOS 11和Xcode 9,试了下iPhone X模拟器上跑公司的项目,发现项目在iPhone ...
    Hank_Zhong阅读 2,500评论 2 3