Notificationz 3.0.0

Notificationz 3.0.0

测试已测试
Lang语言 SwiftSwift
许可 MIT
发布最后发布2019年6月
SPM支持 SPM

mazyod 维护。



Notificationz📡

帮助您拥有自己的 Notification Center

突出特点

  • 保留您的命名约定
    这个库提供了对 NotificationCenter 的便捷访问,但设置方法完全由您自行决定!

  • 无需隐藏
    没有试图隐藏 NotificationCenter 的功能。只是尝试提供一个更方便的 API

  • 全面而简单的测试
    测试这个库很简单,因为它的大部分工作只是转发 NotificationCenter 的调用。Mock 这个对象使测试达到了 100% 的覆盖率。

功能

您可以在框架附带的 playground 中尝试它们!

使用您自己的命名约定来包装 Notification Center

let nsCenter = NotificationCenter.defaultCenter()
let 📡 = NotificationCenterAdapter(notificationCenter: nsCenter)
📡.post("💃")

// my personal preference, define this in Globals.swift
let NC = NotificationCenterAdapter(notificationCenter: nsCenter)
// Now, you can use `NC` throughout the app

四个简单的关键词要记住

NC.add(obj, selector: Selector("call:"))  // normal add observer
NC.observe { notification in }  // observe using blocks
// it's recommended you define your notifications as enums
let name = Notification.Name(rawValue: "Ten-hut!")
NC.post(name)                   // post a notification
NC.remove(obj)                  // remove from nsCenter

透明且便捷的 API

let keys = ["observe", "many", "keys"].map {
    Notification.Name(rawValue: $0)
}
NC.observe(keys) { _ in }       // observe on the same thread
NC.observeUI(keys) { _ in }     // delivered to the main thread

NC.post(notificationName)
NC.post(anotherName, userInfo: ["info":5])
NC.post(Notification(name: differentName, object: nil))

基于 RAII 的观察者

class Dummy {

    // declare the observer as optional
    var broadcastObserver: Observer?

    init() {
        // assign it anywhere you like
        broadcastObserver = NC.observe { [unowned self] _ in
            self.doSomething()
        }.execute() // this is a neat bonus feature
    }

    func doSomething() {
        // exectued twice, since we call "execute" manually
        print("it works!")
    }
}

var dummy: Dummy? = Dummy()
// trigger notification
NC.post(Notification.Name(rawValue: "call doSomething"))
// cleanup is automatic
dummy = nil
// this won't trigger anything
NC.post("Doesn't crash!")

入门

重要:Kitz 仓库完全支持 Swift 3.0 以及它带来的所有变化。如果您仍在使用 Swift 2.x,请使用 v1.0.0

子模块

对于手动安装,您可以直接获取源代码,或者通过 git 子模块,然后只需

  • Notificationz.xcodeproj 文件作为子项目拖入(请确保没有启用 Copy resources
  • 导航到您的顶层项目设置。在“嵌入式二进制”下,点击“+”按钮并选择 Notificationz.framework

动机

在迁移到 Swift 后,NotificationCenter 的 API 在代码中非常突出。为了注册、处理和清理通知,需要在各个地方编写大量的样板代码。由于来自 C++,RAII 似乎是一个非常宝贵的模式可以在这里应用。

使用这个框架,可以轻松地将所有的观察者声明为属性

class Sample {
    private var keyboardObserver: Observer?
    private var reachabilityObserver: Observer?
}

其他程序员应该会对这种一致性感到高兴!并且无需担心在其他函数中的某个地方处理通知,也无需在 deinit 中进行清理。它仅仅如此工作

keyboardObserver = NC.observeUI(UIKeyboardWillShowNotification) { [unowned self] _ in
    // you can write your handler code here, maybe call another function
}

// you can force cleanup by setting the property to nil, but don't have to
keyboardObserver = nil

作者

Mazyod (@Mazyod)

许可

Notificationz 采用 MIT 许可证发布。详细信息请参阅 LICENSE。