Ism*_*ail 2 notifications key-value-observing realm swift
我使用Realm结果对象Result<AnObject>作为数据源uitableview.在不同的视图控制器中有一些后期API调用,可以加载更多AnObject对象.我想要的是在更新数据源以更新表视图时收到通知.我做了一些搜索并且知道我需要使用KVO,但我找不到任何关于如何在realm中使用它的示例.我的代码如下所示:
class myViewController: UIViewController, UITableViewDatasource {
let realm = try! Realm()
override func viewDidLoad() {
super.ViewDidLoad()
var datasource = realm.objects(AnObject.self)
// I need to some how observe the change of datasource
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datasource.count
}
...
}
Run Code Online (Sandbox Code Playgroud)
更新
我realm.addNotificationBlock在它工作之前尝试使用(在@joern答案中使用相同的方式),但是当任何领域对象不仅更新数据类型时,问题就是块将运行.这个表重新加载了太多无意义的时间.
更新2
我的应用程序有一个CalendarViewController,它包含上半部分的FSCalenar视图和下半部分的一个容器,链接到EventsViewController,它有事件的tableview.我有很多事件需要很长时间才能从API中获取.所以我对API进行了大约20次调用,每个API都会获得一些事件.并添加所有调用操作,NSOperationQueue然后根据我需要首先加载的内容设置操作优先级.因此,每个API调用在完成时都会更新数据源对象.我需要事件tableview然后重新下载.API调用发生在CalendarViewController调用的APIManager类方法中
您不必使用KVO.您可以使用Realm的通知功能:
每次提交写入事务时,Realm实例都会向其他线程上的其他实例发送通知.通过注册块可以观察到这些通知:
let token = realm.addNotificationBlock { notification, realm in
let realm = try! Realm()
self.datasource = realm.objects(AnObject.self)
self.tableView.reloadData()
}
Run Code Online (Sandbox Code Playgroud)
只要您对此令牌保持强烈引用,您就会收到通知.
更新:
如果您不想使用Realm的通知,只要API调用返回结果,您就可以发布自己的通知,然后相应地重新加载表视图:
将您添加EventViewController到默认值NSNotificationCenter并添加操作:
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didReceiveReloadNotification:"), name: "RELOAD_NOTIFICATION", object: nil)
...
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func didReceiveReloadNotification(notification: NSNotification) {
let realm = try! Realm()
datasource = realm.objects(AnObject.self)
tableView.reloadData()
}
Run Code Online (Sandbox Code Playgroud)
然后,只要您的一个API请求操作完成后发布通知:
dispatch_async(dispatch_get_main_queue()) { () -> Void in
NSNotificationCenter.defaultCenter().postNotificationName("RELOAD_NOTIFICATION", object: nil)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3897 次 |
| 最近记录: |