RITypedNotification 版本 1.1.0

RITypedNotification 版本 1.1.0

Paul Calnan 维护。



RITypedNotification 版本 1.1.0

  • Paul Calnan

TypedNotification

TypedNotification 微框架允许您使用 NotificationCenter 发布和接收与关联数据相关联的强类型通知,无需手动打包和解析 userInfo 字典。

使用类型通知很简单。首先,定义一个通知类型

struct MyNotification: TypedNotification {
    var value: String
}

然后使用 NotificationCenter 为该通知添加观察者

class MyViewController: UIViewController {
    private var token: NotificationToken?

    override func viewDidLoad() {
        super.viewDidLoad()

        token = NotificationCenter.default.addObserver(for: MyNotification.self) { [weak self] (notification) in
            self?.received(notification)
        }
    }

    private func received(_ notification: MyNotification) {
        print(notification.value)
    }
}

在示例中,MyViewController 保留由 NotificationCenter.addObserver() 返回的 NotificationToken。当 MyViewController 实例被释放时,该 NotificationToken 也会被释放,观察者也会被注销。**[weak self] 捕获列表很重要。如果没有它,将会有一个保留循环,导致内存泄漏。**

最后,使用 NotificationCenter 发布通知

NotificationCenter.default.post(MyNotification(value: "foobar"), from: self)