通知一般在mode與View需要交流(傳遞數據)時使用,或者也可以用于多線程的消息傳遞,也可是VC與VC或者VC內部的信息傳遞,最常用的場景是頁面值的回傳。
下面就介紹一下使用方法
創建通知中心
設置監聽方法
設置通知的名字
NotificationCenter.default.addObserver(self, selector: #selector(test), name: NSNotification.Name(rawValue:"isTest"), object: nil)
實現通知監聽方法
@objc func test(nofi : Notification){
let str = nofi.userInfo!["post"]
print(String(describing: str!) + "this notifi")
}
點擊發送通知進行
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
NotificationCenter.default.post(name: NSNotification.Name("isTest"), object: self, userInfo: ["post":"NewTest"])
}
最后要記得移除通知
deinit {
/// 移除通知
NotificationCenter.default.removeObserver(self)
}
通知的一般使用流程就是這樣了,還有其他的使用流程就自己去嘗試吧