用闭包实现通知的监听事件

  1. 使用
1
2
3
4
5
6
7
8
9
// 通知监听
self.observerNotification(.notifyName1) { notify in
print(notify.userInfo)
}
// 发出通知
self.postNotification(.notifyName1, userInfo: ["infoKey": "info"])

// 移除通知
self.removeNotification(.notifyName1)

  1. 实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public typealias NotificationClosures = (Notification) -> Void
private var notificationActionKey: Void?

// 用于存放通知名称
public enum NotificationNameType: String {
case notifyName1
case notifyName2
}

extension NSObject {
private var notificationClosuresDict: [NSNotification.Name: NotificationClosures]? {
get {
return objc_getAssociatedObject(self, &notificationActionKey)
as? [NSNotification.Name: NotificationClosures]
}
set {
objc_setAssociatedObject(self, &notificationActionKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
}
}
public func postNotification(_ name: NotificationNameType, userInfo: [AnyHashable: Any]?) {
NotificationCenter.default.post(name: NSNotification.Name(name.rawValue), object: self, userInfo: userInfo)
}
public func observerNotification(_ name: NotificationNameType, action: @escaping NotificationClosures) {
if var dict = notificationClosuresDict {
guard dict[NSNotification.Name(name.rawValue)] == nil else {
return
}
dict.updateValue(action, forKey: NSNotification.Name(name.rawValue))
self.notificationClosuresDict = dict
} else {
self.notificationClosuresDict = [NSNotification.Name(name.rawValue): action]
}
NotificationCenter.default.addObserver(self, selector: #selector(notificationAction),
name: NSNotification.Name(name.rawValue), object: nil)
}
public func removeNotification(_ name: NotificationNameType) {
NotificationCenter.default.removeObserver(self)
notificationClosuresDict?.removeValue(forKey: NSNotification.Name(name.rawValue))
}
@objc func notificationAction(notify: Notification) {
if let notificationClosures = notificationClosuresDict, let closures = notificationClosures[notify.name] {
closures(notify)
}
}
}