最近做的一個項目晚岭,有些地方準(zhǔn)備用通知來處理八孝,但是原生的通知使用方式著實惡心到了我董朝,準(zhǔn)備自己寫個,結(jié)果看到GitHub上有類似的項目干跛,就對源碼研究了下子姜,很簡潔,但是把通知的使用方式變的更簡潔楼入。
GitHub項目地址: https://github.com/ZeroFengLee/ZRNotify
先說說使用這個框架哥捕,對于通知的使用方式會有什么改變
以往的通知使用方式:
// 監(jiān)測通知
NotificationCenter.default.addObserver(self, selector: #selector(acceptNotify), name: NSNotification.Name(rawValue: "NotifyName"), object: nil)
func acceptNotify(notify: Notification) {
print(notify)
}
// 發(fā)送通知
NotificationCenter.default.post(name: Notification.Name(rawValue: "NotifyName"), object: "hello")
使用ZRNotify之后的使用方式:
// 監(jiān)測通知
ZRNotify().on("NotifyName", notify: { notify in
print(notify.object)
})
// 發(fā)送通知
NotificationCenter.default.post(name: Notification.Name(rawValue: "NotifyName"), object: "hello")
從上面的代碼可以看出,最大的不同就是在監(jiān)測通知這部分嘉熊,而且監(jiān)測到的通知結(jié)果會以block返回遥赚,不會讓代碼太分散。但是這個框架針對多個通知阐肤,還有一些高級些的玩法凫佛。
一:鏈?zhǔn)奖O(jiān)測讲坎,
ZRNotify().on("ScheduleA", notify: { notify in
print(notify.object)
}).on("ScheduleB", notify: { notify in
print(notify.object)
})
二:統(tǒng)一監(jiān)測處理
notify.ons(["ScheduleA", "ScheduleB"], notify: { notify in
print(notify.object)
})
源碼解讀:
其實源碼主要就是為了解決兩個問題:
1, 結(jié)果回調(diào)
2, 鏈?zhǔn)秸{(diào)用
他使用了一個notifyPool
去管理所有的通知,當(dāng)調(diào)用接口on 和 ons的時候愧薛,將notifyType對象裝載進(jìn)來晨炕。
public typealias notifyType = ((Notification) -> Void)
fileprivate var notifyPool: [(String, notifyType?)] = []
當(dāng)有通知被調(diào)用的時候, 根據(jù)通知名字,去查找notifyType對象毫炉,然后開始回調(diào)
?func receiveNotify(_ notification: Notification) {
for notify in notifyPool {
guard notify.0 == notification.name.rawValue else {
continue
}
notify.1?(notification)
}
}
實現(xiàn)代碼可能比這個稍微復(fù)雜一點瓮栗。使用這個框架的時候,你能明顯感受到對于以往的代碼結(jié)構(gòu)還是有很大的提升瞄勾,有興趣的可以去看下源碼费奸。