在 Android 中,当我们更新它时,我们有可变的实时数据对象,假设我们在另一个线程上附加了一个观察者。 当对象更新时,观察者正在监听并相应地更新 UI。
liveDataService.setValue(response); ==> updating the object with new data
在 Activity 中(比如 TableViewController for swift/IOS)
我们把观察者放在
liveDataService.observeForever(s -> {
Log.d(TAG, getString(R.string.service_observer_message));
updateUI(s);
}); ==> When liveDataService changes we update the UI
现在我想为 Swift/IOS 做同样的事情
我看到了函数
addObserver(_:forKeyPath:options:context:)
但我不能将它附加到一个仅在后台获取 NSObject 更新的数组
完成这项任务的最佳方法是什么?
谢谢 伊兰
最佳答案
据我了解,您应该使用本地通知通过 addObserver 和 postNotification 发送数据来实现这一点。找到相同的示例代码。
let imageData:[String: UIImage] = ["image": image]
//发布通知
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageData)
//注册接收类(class)通知
NotificationCenter.default.addObserver(self, selector: #selector(self.receiveData(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
//处理通知
func receiveData(_ notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
}
}
关于ios - Swift/IOS 如何使用观察者进行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54146841/