[英]Benefits and Disadvantages for subclassing NotificationCenter
我對 Swift 很陌生。 在我看到的所有NotificationCenter
示例中,都使用了默認的NotificationCenter.default
。 但是我已經測試過可以繼承NotificationCenter
並使用自定義對象來發布和收聽通知。
import Foundation
struct Notice {
let num: Int
let str: String
}
class TestObj: NotificationCenter {
private var number = 0
override init() {
number = 5
}
func postNotification(_ num: Int) {
post(name: Notification.Name(rawValue: "TestObjNotification"), object: Notice(num: num, str: "No is \(num)"))
}
}
class Watcher: NSObject {
var obj = TestObj()
func addWatchers() {
obj.addObserver(self, selector: #selector(watched(noti:)), name: Notification.Name(rawValue: "TestObjNotification"), object: nil)
}
func watch(num: Int) {
obj.postNotification(num)
}
@objc func watched(noti: NSNotification) {
print(noti.name.rawValue)
print(noti.object!)
guard let noticeObj = noti.object as? Notice else {
print("Not working")
return
}
print(noticeObj.num)
print(noticeObj.str)
}
}
let watcherObj = Watcher()
watcherObj.addWatchers()
watcherObj.watch(num: 500)
我更喜歡這種方法,因為這樣可以確保將通知分組到特定類型,而不是維護應用程序范圍內的通知。 也可以使用 iOS 12 及之前的這些自定義類型來實現 ObservableObject 功能。 我擔心的是:
NotificationCenter
被解除分配時會發生什么? 所有聽眾都需要停止聽嗎? 當所有偵聽器注冊相同的通知時會發生什么。 由於NotificationCenter.default
是只讀的,因此沒有任何問題。一般來說,您應該更喜歡組合而不是繼承。 我不建議在這里進行子類化。 TestObj不是通知中心。 如果你願意,你可以配置它,使 TestObj有一個通知中心:
class TestObj {
var notificationCenter: NotificationCenter
private var number = 5
override init(notificationCenter: NotificationCenter) {
self.notificationCenter = notificationCenter
}
func postNotification(_ num: Int) {
notificationCenter.post(name: Notification.Name(rawValue: "TestObjNotification"), object: Notice(num: num, str: "No is \(num)"))
}
}
現在您可以自由地擔心任何傳入通知中心的生命周期超出了 TestObj 的生命周期。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.