TypedNotification
TypedNotification 是一个 Swift 库,它为 Foundation 的 NotificationCenter
添加了一些类型安全功能。这个库体积小,可以将它作为一个框架添加到项目中,或者直接包括单个源文件。
使用
参考文档在此处提供:https://alexjohnj.github.io/TypedNotification/.
Playground
此存储库包含一个注释的 playground,演示了 TypedNotification 的功能。要使用它
- 克隆仓库。
- 打开
TypedNotification.xcworkspace
- 为您的 Mac 构建一个 TypedNotification 方案。
- 打开 Demo playground 并运行它。
概述
为应用中的每个通知,创建一个符合 TypedNotification
协议的新类型
struct DataStoreDidSaveNotification: TypedNotification {
/// The data store posting the notification.
let object: DataStore // <- This property is required by the protocol.
let insertedObjects: Set<Model>
}
在遵从协议时,您必须提供一个类型和附加到通知的对象的存储。通常包含在通知的 userInfo
字典中的额外数据可以作为通知的属性提供。
要发布一个通知,创建一个通知的实例,并在 NotificationCenter
上调用 post(_:) 方法的实现
NotificationCenter.default.post(DataStoreDidSaveNotification(object: dataStore, insertedObjects: insertedObjects))
要观察通知,请在 NotificationCenter
上使用 addObserver(forType:object:queue:using)
方法。这与 Foundation 方法类似,但观察的是通知类型而不是名称,并返回一个 NotificationObservation
来管理观察。
let observation = NotificationCenter.default.addObserver(forType: DataStoreDidSaveNotification.self, object: nil, queue: nil) { note in
print(note.insertedObjects)
}
注意,传递给回调块的 note
类型的值是 DataStoreDidSaveNotification
。
返回的 NotificationObservation
实例管理观察的生命周期。当实例被释放时,观察也随之停止。
通知观察袋子
TypedNotification 为使用 NotificationObservation
提供了一个方便的类型。一个 NotificationObservationBag
存储多个观察实例,并在释放时删除它们。您可以使用它将观察的生命周期与另一个对象绑定。
class ViewController: UIViewController {
let notificationBag = NotificationObservationBag()
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(forType: DataStoreDidSaveNotification.self, object: nil, queue: nil) { [unowned self] note in
self.doSomething(with: note.insertedObjects)
}
.stored(in: notificationBag)
}
}
在这里,当 ViewController
被释放时,它的通知袋子也会被释放,以及 viewDidLoad()
中设置的观察也随之消失。
这种行为非常有用,所以 TypedNotification 包括一个针对常规 Notification
的 addObserver
变体,它也返回一个 NotificationObservation
。
func setUpKeyboardObservation() {
NotificationCenter.default.addObserver(forNotificationNamed: UIWindow.keyboardWillShowNotification, object: nil, queue: nil) { note in
print(note.userInfo?[UIWindow.keyboardFrameEndUserInfoKey])
}
.stored(in: notificationBag)
}
需求 & 安装
TypedNotification 需要一个可以编译 Swift 5 代码的 Xcode 版本。此外,它还需要一个针对 iOS 10+ 或 macOS 10.12+ 的部署目标,因为依赖于 os.lock
。
您有四种安装选项。
手动安装
将 TypedNotification.swift
从 Sources
目录复制下来。
CocoaPods
将以下内容添加到您的 Podfile
中
pod 'AJJTypedNotification', '~> 2.0'
注意,模块名称(即您 import
的内容)是 TypedNotification,但库是 AJJTypedNotification。
Carthage
将以下内容添加到您的 Cartfile
github "alexjohnj/TypedNotification" ~> 2.0
Swift Package Manager
将以下内容添加到您的 Package.swift
文件的依赖项中
dependencies: [
.package(url: "https://github.com/alexjohnj/TypedNotification.git", .upToNextMinor(from: "2.0.0"))
]
许可证
MIT