SimpleNotification 0.5

SimpleNotification 0.5

Viktor Kalinchuk 维护。



  • Viktor Kalinchuk

SimpleNotification

CI Status

SimpleNotification 是一个轻量级的包装器,它可以帮助您更容易地处理观察者模式,而不是使用老式的 buddy NotificationCenter。

特性

  • 处理闭包,而不是选择器
  • 使用具有用户数据对象类型定义在编译时的强大类型化观察者块
  • 支持自定义和系统通知

示例

要运行示例项目,首先克隆仓库,然后从 Example 目录运行 pod install

观察一个预期发送 Data 对象的通知的简单示例

// Registering for a notification
let dumbDateObserver: NotificationObserver<Date> = NotificationObserver(event: "Example event") { item in
    // item variable is guaranteed to be type of Date
}

// Sending a notification
NotificationEmitter.fire(event: "Example event", associatedObject: Date())

如果用户数据作为通知发送的对象类型不重要,或者它发送没有任何东西

// Registering for a notification
let dumbNilObserver: NotificationObserver<Any> = NotificationObserver(event: "Another event") { _ in
    // Your code here
}

// Sending a notification
NotificationEmitter.fire(event: "Another event")

一个合理的问题:“如果预期发送一个类型的对象,但发送的是另一个类型的对象会发生什么?”答案是:这取决于您的需求。在注册事件时,您可以传递一个可选参数 policy。有三个选项:引发致命错误、引发断言或跳过。默认情况下,它使用 .assert 值,但您可以使用任何。

let dateObserver = NotificationObserver<Date>(event: "Example event", policy: fatalError("Wow, so unexpected!")) { item in
    // Your code here
}

// Causes fatal error
NotificationEmitter.fire(event: "Example event", associatedObject: "I'm a string!")

然而,如果了对意外关联类型默认行为的处理不是您需要的,您可以通过传递 inconsistentObjectHandler 参数来自定义处理。

安装

SimpleNotification 可通过 CocoaPods 获取。要安装它,只需将以下行添加到您的 Podfile 文件

pod 'SimpleNotification'

作者

Viktor Kalinchuk,[email protected]

许可

SimpleNotification 在 MIT 许可下可用。有关更多信息,请参阅 LICENSE 文件。