通知简介
通知(Notification)是观察者模式(observer)中的一种, 结构为: 发布者 -> 通知中心 -> 接收者, 是iOS 开发中常用通信方式,为单例模式使用。可以实现一对一、一对多通信。
原理如下图:
传统通知使用
监听通知
/// 监听通知
private func registerNoti() -> Void {
NotificationCenter.default.addObserver(self, selector: #selector(receive(noti:)), name: NSNotification.Name("viewNotiSecond"), object: nil)
}
发送通知
/// 发送通知
func postNoti() -> Void {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "viewNotiSecond"), object: nil, userInfo: nil)
}
更优雅的使用通知
何为更优雅,有Swfit语言风格兼顾便于统一与管理[当有多个通知或者Selector方法]
扩展Notification.Name
extension Notification.Name {
static let viewNotiSecond = Notification.Name(rawValue: "viewNotiSecond")
}
扩展Selector
fileprivate extension Selector {
static let viewNotiSecond = #selector(ViewController.receive(noti:))
}
注册通知
注册通知时,只需要通过点语法即可,而Selector扩展前加入权限控制防止污染其他地方的扩展。
/// 注册通知
private func registerNoti() -> Void {
NotificationCenter.default.addObserver(self, selector: .viewNotiSecond, name: .viewNotiSecond, object: nil)
}
发送通知
/// 发送通知
func postNoti() -> Void {
NotificationCenter.default.post(name: .viewNotiSecond, object: nil, userInfo: nil) //直接通过点语法即可
}
注意操作
由于通知是单列的,所以使用完后必须在析构deinit中移除通知,否则后期将引发难以查询的莫名错误
deinit {
// 移除通知
NotificationCenter.default.removeObserver(self)
NotificationCenter.default.removeObserver(self, name: .viewNotiSecond, object: nil) // 移除特定通知
}
总结
传统方法缺点,容易导致发送端与注册端通知名字拼写错误
优雅的方式,缺陷是可能会增加一点代码, 优点是增加代码模块性,避免拼写错误。统一管理方法。