一个极简且有效的 NSNotificationCenter
替代品,它提倡观察者模式并保持对其观察者的弱引用。
功能
enum
作为通知# Swift 3
github "nodes-ios/Noted" ~> 2.0
# Swift 2
github "nodes-ios/Noted" ~> 1.0
Noted 本身是一个单例,您可以从应用程序中的任何位置访问它,并且对于轻松向路由器和/或任何其他类发送消息可能特别有用。
开始使用
import Noted
您需要实现两个协议才能使 Noted 工作。一个用于通知(对象/结构/枚举),也称为 Note
,第二个用于您要添加的每个观察者。
Note 类型
只需让您的对象符合它,就可以了!
我们建议使用 enum
,因为您可以充分利用 Swift,并且可以关联值,而无需将它们包装在带有字符串键的丑陋字典中。
enum Note: NoteType {
case ShowLoginFlow
case SignupForPush(userId: Int)
}
Note 观察者
观察者协议要求您实现一个函数 didReceive(note: NoteType)
,每次发送通知并且您的观察者被添加为观察者时,都会调用该函数。
注意: 此函数将在主线程上执行。
class ViewController: UIViewController, NoteObserver {
// MARK: - Note Observer -
func didReceive(note: NoteType) {
switch note {
case .SingupForPush(let userId):
print(userId)
}
}
}
Noted 支持三个操作
*所有观察者在 Noted 中都有弱引用,因此如果您希望它们在 deinit 时消失,则无需手动移除观察者。
func viewDidLoad() {
super.viewDidLoad()
Noted.defaultInstance.add(observer: self)
}
注意: 您需要保持对观察者的强引用,否则它将在添加后立即被移除。
func viewWillDisappear() {
super.viewWillDisappear()
Noted.defaultInstance.remove(observer: self)
}
发送 notes 非常简单,只需调用 post(note: note)
即可立即发送。
func buttonPressed() {
Noted.defaultInstance.post(note: Note.SignupForPush(userId: 1))
}
注意: 请注意,Noted 使用后台线程并将 post 操作与观察者的添加和移除同步。
如果您发送大量通知并且有很多观察者,则本节可能对您有用。
Noted 提供了一个选项来过滤哪些观察者将接收通知,默认情况下使用 PassthroughNoteFilter
,让所有通知都通过。
您可以通过在观察者上提供您自己的 NoteFilter
来覆盖此行为。
struct RandomFilter: NoteFilter {
func shouldFilter(note: NoteType) -> Bool {
return arc4random() % 10 < 5
}
}
class TestObserver: NoteObserver {
let noteFilter: NoteFilter = RandomFilter()
func didReceive(note: NoteType) { }
}
注意: 除非您有 #courage,否则不要使用上面提供的过滤器。
用 ❤️ 在 Nodes 制作。
Noted 在 MIT 许可证下可用。有关更多信息,请参阅 LICENSE 文件。