ios - Swift/IOS 如何使用观察者进行更新

标签 ios swift

在 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 更新的数组

完成这项任务的最佳方法是什么?

谢谢 伊兰

最佳答案

据我了解,您应该使用本地通知通过 addObserverpostNotification 发送数据来实现这一点。找到相同的示例代码。

 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/

相关文章:

ios - 根据按下的单元格更改 UITableViewCell 选择颜色

swift - 使用自定义函数删除表格 View 单元格

swift - 在WebView上解析和查看文件

iphone - 如何检测 UITableView 上的 "quick touch"以便切换到全屏或从全屏切换?

ios - 如何访问父类(super class)初始化期间定义的属性

arrays - 在 Swift 中使用 .filter 和字典数组

ios - 我可以要求用户重新验证 Apple ID 登录吗

ios - Swift PageViewController 渐变背景

ios - 重用 View Controller 及其 ivars、scrollviews、tableview

ios - 在 iOS 中显示所有可用的 wifi 网络