一个以协议为核心的 NotificationCenter,它具有类型安全、线程安全和内存安全。
-
类型安全
不再有
userInfo
字典和向下转型,只需将具体的类型值传递给观察者即可。 -
线程安全
您可以在任何线程中
register
、notify
、unregister
而不会崩溃和数据损坏。 -
内存安全
SwiftNotificationCenter
将观察者存储为零初始化的弱引用。无需崩溃也不需要手动unregister
。
它很简单、安全、轻量级且易于使用,适用于 一对多
通信。
使用方法
定义协议和观察者
protocol Update {
func updateTitle(title: String)
}
extension ViewController: Update {
func updateTitle(title: String) {
self.titleLabel.text = title
}
}
let vc = ViewController()
注册
Broadcaster.register(Update.self, observer: vc)
广播
Broadcaster.notify(Update.self) {
$0.updateTitle("new title")
}
注销
Broadcaster.unregister(Update.self, observer: self)
与 NSNotificationCenter
进行比较
例如,处理 UIKeyboardWillShowNotification
@objc func handleKeyboardNotification(notification: NSNotification) {
guard notification.name == NSNotification.Name.UIKeyboardWillShow
else { return }
guard let beginFrame = (notification
.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
else { return }
guard let endFrame = (notification
.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
else { return }
// use beginFrame, endFrame
}
SwiftNotificationCenter
方法
/*
If you want to observe the system built in notifications like this.
You can declare a protocol and the relevant method, and use a singleton as a mediator to observe system's notification, then notify our observers.
Please check the refactor example in SwiftNotificationCenterExample Project.
*/
func UIKeyboardWillShow(beginFrame: CGRect, endFrame: CGRect) {
}
安装
CocoaPods
pod 'SwiftNotificationCenter'
Carthage
github "100mango/SwiftNotificationCenter"
手动
只需将 SwiftNotificationCenter 文件夹中的源文件复制到您的项目中即可。
许可证
SwiftNotificationCenter
采用了 MIT 许可证。