1:發送通知方法一:
name:一般情況下我們需要定義成一個常量, 如:kNotiAddPhoto
object:(誰發送的通知) 一般情況下我們可以不傳,置為nil表示<匿名發送> ,如果我們只需要傳入一個參數的話,比如說本身控制器或者該類中的某一個控件的話,我們就可以使用object傳出去,例子如下
NotificationCenter.default.post(name: <#T##NSNotification.Name#>, object: <#T##Any?#>)
// 由於事件要多級傳遞,所以才用通知,代理和回調其實也是可以的 NotificationCenter.default.post(name: NSNotification.Name(rawValue: kNotiAddPhoto), object: nil)
只傳入一個object:參數的控件:
@IBAction func closeBtnClick() { NotificationCenter.default.post(name: NSNotification.Name(rawValue: kNotiRemovePhoto), object: imageView.image) }
傳入多個參數需要使用userInfo傳入:
NotificationCenter.default.post(name: <#T##NSNotification.Name#>, object: <#T##Any?#>, userInfo: <#T##[AnyHashable : Any]?#>)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "你定義的名字name"), object: nil, userInfo:["name" : "XJDomain", "age" : 18])
1.1接收通知方法一:
NotificationCenter.default.addObserver(<#T##observer: Any##Any#>, selector: <#T##Selector#>, name: <#T##NSNotification.Name?#>, object: <#T##Any?#>)
// 接受添加圖片的通知 NotificationCenter.default.addObserver(self, selector: #selector(addPhoto), name: Notification.Name.init(rawValue: kNotiAddPhoto), object: nil)
上面通知調用方法: 沒有參數的方法
// 添加照片 @objc fileprivate func addPhoto(){ // 方法調用 }
--------------------------------------------------------------
// 接受刪除圖片的通知 NotificationCenter.default.addObserver(self, selector: #selector(removePhoto(noti:)), name: NSNotification.Name(rawValue: kNotiRemovePhoto), object: nil)
上面通知調用方法: 有參數的方法
// 刪除照片 @objc fileprivate func removePhoto(noti : Notification) { guard let image = noti.object as? UIImage else { return } guard let index = images.index(of: image) else { return } images.remove(at: index) picPickerCollectionView.images = images }
1.2移除通知:
在接收通知控制器中移除的,不是在發送通知的類中移除通知的
// 移除通知<通知移除是在發通知控制器中移除> deinit { NotificationCenter.default.removeObserver(self) }
1.3 高手使用的通知:
在接收通知的時候有另外一個方法:
好處是:不需要我們再寫一個方法
壞處是:移除通知相比麻煩,但是還好
// name: 通知名字 // object :誰發出的通知,一般傳nil // queue :隊列:表示決定block在哪個線程中去執行,nil表示在發布通知的線程中執行 // using :只要監聽到了,就會執行這個block // 一定要移除,不移除的話會存在壞內存訪問,移除的話需要定義一個屬性observe來接收返回對象,然后在移除方法中移除即可 observe = NotificationCenter.default.addObserver(forName: Notification.Name.init(rawValue: kNotiAddPhoto), object: nil, queue: nil) { (Notification) in print("-------------",Thread.current) }
移除通知:
01-先定義一個屬性
weak var observe : NSObjectProtocol?
02-接收通知返回來的觀察者
observe = NotificationCenter.default.addObserver(forName: Notification.Name.init(rawValue: kNotiAddPhoto), object: nil, queue: nil) { (Notification) in print("-------------",Thread.current) }
03-在移除通知方法中移除通知
// 移除通知<通知移除是在發通知控制器中移除> deinit { //NotificationCenter.default.removeObserver(self) NotificationCenter.default.removeObserver(observe!) }