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我用这个姿势来管理
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 【蝴蝶效应】 蝴蝶效应:上个世纪70年代,美国一个名叫洛伦兹的气象学家在解释空气系统理论时说,亚马逊雨林一只蝴蝶...