Notification

监听还可以发送信息

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)
    }
    
    // 接收通知后的方法回调
    @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) 获取到通知,用户数据是[\(value1),\(value2)]")
        
        sleep(3)
        
        print("\(name) 执行完毕")
    }
    
    deinit {
        //移除通知监听
        NotificationCenter.default.removeObserver(self)
    }
}
let observers = [MyObserver(name: "观察器1"),MyObserver(name: "观察器2")]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        print("发送通知")
        
        let notificationName = Notification.Name(rawValue: "DownloadImageNotification")
        
        // 发送通知
        NotificationCenter.default.post(name: notificationName, object: self,
                                        userInfo: ["value1":"hangge.com", "value2" : 12345])
        
        print("通知完毕")
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容