TypedNotification

TypedNotification 是一个 Swift 库,它为 Foundation 的 NotificationCenter 添加了一些类型安全。该库很小,可以通过框架或直接包含单个源文件添加到您的项目中。

用法

参考文档可在此处获取:here

Playground

此存储库包含一个带有注释的 playground,演示了 TypedNotification 的功能。要使用它,请执行以下操作:

  1. 克隆存储库。
  2. 打开 TypedNotification.xcworkspace
  3. 为您的 Mac 构建 TypedNotification scheme。
  4. 打开 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 实例管理观察的生命周期。当实例被释放时,观察停止。

Notification Observation Bags (通知观察包)

TypedNotification 提供了一种方便的类型来处理 NotificationObservationNotificationObservationBag 存储多个观察实例,并在释放时删除所有实例。您可以使用它将观察的生命周期与另一个对象绑定。

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 包含一个用于普通 NotificationaddObserver 变体,它也返回一个 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

您有四种安装选择。

手动安装

Sources 目录复制 TypedNotification.swift 文件。

CocoaPods

将以下内容添加到您的 Podfile

pod 'AJJTypedNotification', '~> 2.0'

请注意,模块的名称(即您 import 的内容)是 TypedNotification,但 pod 是 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