Swift/IOS如何使用观察员进行更新
在安卓系统中,当我们更新它时,我们有可变的实时数据对象,比如说在一个不同的线程上,我们附加了一个观察者。 当对象更新时,观察者正在监听并相应地更新UISwift/IOS如何使用观察员进行更新,ios,swift,Ios,Swift,在安卓系统中,当我们更新它时,我们有可变的实时数据对象,比如说在一个不同的线程上,我们附加了一个观察者。 当对象更新时,观察者正在监听并相应地更新UI liveDataService.setValue(response); ==> updating the object with new data 并且在活动中(比如说像用于swift/IOS的TableViewController) 我们把观察员 liveDataService.observeForever(s -> {
liveDataService.setValue(response); ==> updating the object with new data
并且在活动中(比如说像用于swift/IOS的TableViewController)
我们把观察员
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
完成这项任务的最佳方法是什么
谢谢
Eran根据我的理解,您应该使用本地通知通过addObserver和postNotification发送数据来实现这一点。查找相同的示例代码
let imageData:[String: UIImage] = ["image": image]
//张贴通知
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageData)
func receiveData(_ notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
}
}
//注册以在类中接收通知
NotificationCenter.default.addObserver(self, selector: #selector(self.receiveData(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
//处理通知
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageData)
func receiveData(_ notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
}
}
有多种方法可以做到这一点 最接近您的Android解决方案的应该是关键值:
如果您想阅读有关该主题的更多信息:您可以使用didSet属性。当属性值更改时,它会响应
var dataArray = [String]() {
didSet {
print(“Array Count = \(dataArray.count)”)
}
}
在dataArray中追加数据时,调用dataArray属性观察并打印数组计数