Notification

監(jiān)聽還可以發(fā)送信息

class MyObserver {
    
    var name:String = ""
    
    init(name:String){
        
        
        self.name = name
        
        // 定義 通知名
        let notificationName = Notification.Name(rawValue: "DownloadImageNotification")
        
        // 自定義一個通知
        NotificationCenter.default.addObserver(self,
                                               selector:#selector(downloadImage(notification:)),
                                               name: notificationName, object: nil)
    }
    
    // 接收通知后的方法回調(diào)
    @objc func downloadImage(notification: Notification) {
        let userInfo = notification.userInfo as! [String: AnyObject]
        let value1 = userInfo["value1"] as! String
        let value2 = userInfo["value2"] as! Int
        
        print("\(name) 獲取到通知,用戶數(shù)據(jù)是[\(value1),\(value2)]")
        
        sleep(3)
        
        print("\(name) 執(zhí)行完畢")
    }
    
    deinit {
        //移除通知監(jiān)聽
        NotificationCenter.default.removeObserver(self)
    }
}
let observers = [MyObserver(name: "觀察器1"),MyObserver(name: "觀察器2")]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        print("發(fā)送通知")
        
        let notificationName = Notification.Name(rawValue: "DownloadImageNotification")
        
        // 發(fā)送通知
        NotificationCenter.default.post(name: notificationName, object: self,
                                        userInfo: ["value1":"hangge.com", "value2" : 12345])
        
        print("通知完畢")
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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