CleanNotification 1.3

CleanNotification 1.3

测试已测试
语言语言 SwiftSwift
许可 MIT
发布最后发布2015年9月
SPM支持 SPM

Lucas IhlströmLucas Ihlström 维护。



  • 作者:
  • Lucas

CleanNotification 是尝试让 Swift 中的通知更合理。

特性

  • 类型安全。包括通知名称和通知内容(发送者和值)。
  • 易于使用。注册、取消注册和发送只需要一行代码。
  • 源安全。通知只能在其定义的文件中发布。
  • 线程安全。即使在其他线程中发布通知,它也总是会在预期的线程上交付(默认为主线程)。

要求

  • iOS 8.0+ / Mac OS X 10.9+
  • Xcode 6.1

安装

示例

注册

为一个通知注册

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)
}

完整示例

Dog.swift

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)
    }
}

ViewController.swift

@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。