在生产中使用Realm Collection Change通知

Rya*_*die 5 realm ios swift

从文档中,我正在使用类似的东西来基于模型更改动态更新表视图:

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通知在通知块内触发,以确保主线程永远不会被阻塞?

TiM*_*TiM 2

从文档的更改通知部分来看,这一点可能并不明显,但实际上文档中已对此进行了介绍。

\n\n

Results对象是实时的、自动更新的对象。当它们的值在应用程序的其他地方(或在后台线程上)更改时,它们将在运行循环的下一次迭代中自动更新为新值(有一些警告。Results在后台线程上需要显式更新)。

\n\n

更改通知的目的只是告诉您发生了更改,并且下次您访问 时results,新值将已经存在。这样您就可以相应地更新 UI。

\n\n

因此,您不需要额外的代码。results只需确保触发更改通知块时,刷新 UI 时仍然引用相同的父对象,并且它应该正常工作\xe2\x84\xa2。:)

\n