众所周知,全局通知多处修改的需求时常有,除非是用响应式框架,否则业务代码一堆堆,实属麻烦。有没有好的方法可以少写代码少加班呢?拯救不开心,拒绝加班,给你一个我自己写的工具代码。
实现方案:利用oc的动态性给对象增加存储属性;利用存储属性搭配工具单例记录执行通知回调的closure来达到多处通知的目的。
上代码:
@objc public extension NSObject {
@objc func registerNotification(name: String, _ closure: @escaping (() -> ())) {
registerNotification(name: name) { _ in closure() }
}
@objc func registerNotification(name: String, receivedCompletion: @escaping ((_ notification: Notification?) -> ())) {
MOJiNotificationHelper.set(object: self, key: name, closure: receivedCompletion)
}
@objc func removeNotifications() { MOJiNotificationHelper.reset(object: self) }
}
class MOJiNotificationHelper: NSObject {
private static var shared = MOJiNotificationHelper()
private var closuresForKeys = [String: [String: (