NSNotificationCenter中addObserver和removeObserver成對(duì)出現(xiàn)的問題

把下邊的code放在storyboard中執(zhí)行(靈活的注釋一些行),可以看到一下效果:
1.多次addObserver,會(huì)導(dǎo)致對(duì)應(yīng)的方法執(zhí)行多次;
2.多次addObserver,一次remove,雖然不能把多有notification移除掉,但是只要所在容器類析構(gòu),就會(huì)移除掉其所有的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)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • http://potter528.bj.bdysite.com最近在做平板的過程中,發(fā)現(xiàn)了一些很不規(guī)范的代碼。偶然...
    Bug集閱讀 772評(píng)論 0 0
  • 1.自定義控件 a.繼承某個(gè)控件 b.重寫initWithFrame方法可以設(shè)置一些它的屬性 c.在layouts...
    圍繞的城閱讀 3,704評(píng)論 2 4
  • 原文出處: http://www.androidchina.net/6174.html Notification在...
    木木00閱讀 12,545評(píng)論 3 32
  • 閑來無事,翻起一本本厚實(shí)的影集,那里面有我的青春,也有很多美好的回憶。 人生的第一張照片是和妹妹的合影,那時(shí)我七歲...
    簡(jiǎn)兒的十年閱讀 396評(píng)論 33 32
  • 前言: 剛更新了iOS 11和Xcode 9,試了下iPhone X模擬器上跑公司的項(xiàng)目,發(fā)現(xiàn)項(xiàng)目在iPhone ...
    Hank_Zhong閱讀 2,570評(píng)論 2 3

友情鏈接更多精彩內(nèi)容