import Foundation
import UIKit
// 利用協議優化通知
protocol Notifier {
// 添加一個關聯的類型
associatedtype Notification: RawRepresentable
}
extension Notifier where Notification.RawValue == String {
static func nameFor(notification: Notification) -> String {
return "\(notification.rawValue)"
}
}
class Barista: Notifier {
/// 發送通知
static func post(notification: Notification, object:AnyObject? = nil) {
let name = nameFor(notification: notification)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: name), object: object)
}
/// 增加觀察 - 接收通知
static func add(observer: AnyObject, selector: Selector, notification: Notification, object:AnyObject? = nil) {
let name = nameFor(notification: notification)
NotificationCenter.default
.addObserver(observer, selector: selector, name: NSNotification.Name(rawValue: name), object: object)
}
/// 移除觀察 - 移除通知
static func remove(observer: AnyObject, notification: Notification, object:AnyObject? = nil) {
let name = nameFor(notification: notification)
NotificationCenter.default.removeObserver(observer, name: NSNotification.Name(rawValue: name), object: object)
}
}
// 定義的通知名字
extension Barista {
enum Notification: String {
/// 開心
case happy
/// 傷心
case sad
/// 睡覺
case sleep
}
}
/*
* 添加: _ = Barista.add(observer: self, selector: #selector(reload), notification: .happy)
* 移除: Barista.remove(observer: self, notification: .happy)
* 發出通知: Barista.post(notification: .happy)
*/
小知識四、NotificationCenter 的key我用這個姿勢來管理
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
- 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
- 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
- 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
推薦閱讀更多精彩內容
- 【蝴蝶效應】 蝴蝶效應:上個世紀70年代,美國一個名叫洛倫茲的氣象學家在解釋空氣系統理論時說,亞馬遜雨林一只蝴蝶...