测试已测试 | ✓ |
语言语言 | SwiftSwift |
许可 | MIT |
发布最后发布 | 2015年9月 |
SPM支持 SPM | ✗ |
由 Lucas Ihlström、Lucas Ihlström 维护。
CleanNotification 是尝试让 Swift 中的通知更合理。
为一个通知注册
DogDidBarkNotification.register(self) {
dog, bark in
println("\(dog.name) barked with decibel: \(bark.decibel) at target: \(bark.target)")
}
或者使用自定义语法
DogDidBarkNotification <<- self - {
dog, bark in
println("\(dog.name) barked with decibel: \(bark.decibel) at target: \(bark.target)")
}
您还可以匿名注册
//Since we're not supplying a token, we cannot unregister later on.
DogDidBarkNotification <<- {
dog, bark in
println("\(dog.name) barked with decibel: \(bark.decibel) at target: \(bark.target)")
}
发布通知
didBarkProducer.produce(self, value: Bark(decibel: 80.0, target: "John Doe"))
或者使用自定义语法
didBarkProducer - self ->> Bark(decibel: 80.0, target: "John Doe")
从通知中取消注册
DogDidBarkNotification.unregister(self)
或者使用自定义语法
DogDidBarkNotification -= self
按照以下方式定义通知
private let didBarkProducer = NotificationProducer<Dog, Bark>()
let DogDidBarkNotification = Notification<Dog, Bark>(producer: didBarkProducer)
第一个泛型参数是通知的发送者(在本例中是 Dog),第二个(在本例中是 Bark)是通知值,可以将其视为 userInfo。
生产者允许 Dog 类成为通知的独家发布者。但如果您想允许任何文件、任何地方的文件发布通知,请使用 OpenNotification
let DogDidBarkNotification = OpenNotification<Dog, Bark>()
如果您想更改通知发布的线程,请在构造函数中指定它
let DogDidBarkNotification = Notification<Dog, Bark>(producer: didBarkProducer, deliveryPolicy: .SenderThread)
可用的交付策略
public enum ThreadDeliveryPolicy {
case MainThread
case SenderThread
case CustomDispatchQueue(dispatch_queue_t)
}
struct Bark {
let decibel: Double
let target: String
}
private let didBarkProducer = NotificationProducer<Dog, Bark>()
let DogDidBarkNotification = Notification<Dog, Bark>(producer: didBarkProducer)
class Dog {
let name: String
init(name: String) {
self.name = name
}
func bark(target: String) {
didBarkProducer - self ->> Bark(decibel: 80.0, target: target)
}
}
@IBAction func buttonPressed(sender: UIButton) {
let dog = Dog("Buddy")
dog.bark("John Doe")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
DogDidBarkNotification <<- self - {
dog, bark in
println("\(dog.name) barked with decibel: \(bark.decibel) at target: \(bark.target)")
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
DogDidBarkNotification -= self
}
CleanNotification 是在 MIT 许可下发布的。详情请参阅 LICENSE。