从文档中,我正在使用类似的东西来基于模型更改动态更新表视图:
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
}
}
Run Code Online (Sandbox Code Playgroud)
文档并没有实际详细说明表的数据源委托如何获取更改后的数据,因此我想出了一个带有自定义getter的属性可以做到的:
var rows: Results<Message> {
let realm = try! Realm()
return result = realm.objects(Message).filter("someQuery == 'something'").sorted("timeStamp", ascending: true)
}
Run Code Online (Sandbox Code Playgroud)
这在实践中效果很好,但是评论Results are now populated and can be accessed without blocking the UI使我对这种方法提出了质疑。我的getter是否应该返回一个空数组,直到.Initial通知在通知块内触发,以确保主线程永远不会被阻塞?
| 归档时间: |
|
| 查看次数: |
2357 次 |
| 最近记录: |