【发布时间】:2016-05-21 09:09:51
【问题描述】:
From the docs,我正在使用类似的东西来根据模型更改动态更新表格视图:
let results = realm.objects(Message).filter("someQuery == 'something'").sorted("timeStamp", ascending: true)
// Observe Results Notifications
notificationToken = results.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in
guard let tableView = self?.tableView else { return }
switch changes {
case .Initial:
// Results are now populated and can be accessed without blocking the UI
tableView.reloadData()
break
case .Update(_, let deletions, let insertions, let modifications):
// Query results have changed, so apply them to the UITableView
tableView.beginUpdates()
tableView.insertRowsAtIndexPaths(insertions.map { NSIndexPath(forRow: $0, inSection: 0) },
withRowAnimation: .Automatic)
tableView.deleteRowsAtIndexPaths(deletions.map { NSIndexPath(forRow: $0, inSection: 0) },
withRowAnimation: .Automatic)
tableView.reloadRowsAtIndexPaths(modifications.map { NSIndexPath(forRow: $0, inSection: 0) },
withRowAnimation: .Automatic)
tableView.endUpdates()
break
case .Error(let error):
// An error occurred while opening the Realm file on the background worker thread
fatalError("\(error)")
break
}
}
文档并没有详细说明表的数据源委托如何获取这些更改的数据,因此我认为使用自定义 getter 的属性可以做到:
var rows: Results<Message> {
let realm = try! Realm()
return result = realm.objects(Message).filter("someQuery == 'something'").sorted("timeStamp", ascending: true)
}
这在实践中效果很好,但Results are now populated and can be accessed without blocking the UI 的评论让我质疑这种方法。我的 getter 是否应该返回一个空数组,直到在通知块中触发 .Initial 通知以确保主线程永远不会被阻塞?
【问题讨论】:
-
您能否展示如何将
results加载到您的UITableView委托方法中?您是否使用表使用的results填充单独的数组?还是你的表直接访问results?