我对斯威夫特很陌生。在我看到的所有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)我更喜欢这种方法,因为这样可以确保将通知分组到特定类型,而不是维护整个应用程序的通知。此外,还可以为ObservableObject 12及之前使用这些自定义类型来实现iOS功能。我担心的是:
NotificationCenter被解除分配时会发生什么?难道所有的听众都需要停止听吗?当所有侦听器注册相同的通知时会发生什么。因为NotificationCenter.default是只读的,所以这方面没有任何问题。发布于 2021-06-10 07:35:00
一般来说,你应该更喜欢构图而不是继承。我不建议在这里做子类。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生存期之外的任何传入通知中心的生存期。
https://stackoverflow.com/questions/67916388
复制相似问题