MCNotificationCenter
是 NSNotificationCenter 的替代品,它简化了处理通知的过程。单例类管理并跟踪注册的观察者,您无需处理!使用 MCNotificationCenter
防止在注册观察者时发送通知导致的观察者崩溃。
使用 Cocoapods
$ pod 'MCNotificationCenter'
或者将 MCNotificationCenter.swift
和 NSObject+EasyKVO.swift
复制到项目中。如果需要,将其添加到桥接头文件中。
请查阅仓库中的示例项目,以获取完整的代码示例。
所有调用都应使用 MCNotificationCenter.defaultCenter
单例
MCNotificationCenter.defaultCenter
使用提供的方法之一添加一个观察者。它遵循类似于 NSNotificationCenter 的结构。
MCNotificationCenter.defaultCenter.addObserver(self, selector: Selector("printNotification:"), name: "myNotification", object: nil)}
移除一个观察者。检查观察者是否存在是可选的,即使观察者不存在,调用 remove 也是安全的。
if MCNotificationCenter.defaultCenter.isObserverForName("myNotification", observer: self) {
MCNotificationCenter.defaultCenter.removeObserverWithName("myNotification", observer: self)
}
注意:您可以从类或对象中删除所有已注册的观察者。
使用闭包添加一个键值观察者(实现此功能需要设置 MCNotificationCenter.defaultCenter。要实现不同的观察者类,将类设置为观察者并将块设置为 nil)
MCNotificationCenter.defaultCenter.addKeyValueObserver(MCNotificationCenter.defaultCenter, onObject: self.myObject, forKeyPath: "someValue", options: .New, context: nil) { () -> () in
println(self.myObject.someValue)
}
或者使用 NSObject+EasyKVO
扩展,它提供了使用 MCNotificationCenter 函数的便捷方法
myObject.addObserver("someValue", usingBlock: { () -> () in
println(self.myObject.value)
})
并且可以使用键路径轻松删除
myObject.removeObserver("someValue")
请查看文件和代码注释。
有问题、评论或想法?随时给我发消息或提交问题。
欢迎为修复、添加、改进或其他有趣的内容提交拉取请求。