TypedNotificationCenter
此框架旨在重新思考 Apple 的 NotificationCenter,使其更安全类型化,并消除 userInfo 字典中所需值存在的未知性。
示例使用
// SampleNotification.swift
import TypedNotificationCenter
enum SampleNotification: TypedNotification {
struct Payload {
let type = "test"
}
typealias Sender = MyCustomView
}
// OtherFile.swift
// Observe a notification and execute a block with the sender and the payload
var observations = [TypedNotificationObservation]()
observations.append(TypedNotificationCenter.default.observe(SampleNotification.self, object: nil, block: { (sender, payload) in
print(sender, payload)
}))
// Post a notification
TypedNotificationCenter.default.post(SampleNotification.self, sender: self, payload: SampleNotification.Payload())
// Stop observing the notification, this is also called when the observation object deinitializes
observation?.invalidate()