【问题标题】:Using Realm Collection Change notifications in production在生产环境中使用 Realm Collection Change 通知
【发布时间】: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

标签: ios swift realm


【解决方案1】:

从文档的更改通知部分可能并不明显,但实际上已涵盖 here in the docs

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

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

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

【讨论】:

  • 通过额外的代码,您指的是我的吸气剂还是在.Initial 被解雇之前不返回任何结果的需要?感谢您的回答,Realm 很棒!
  • 我注意到文档将部分硬编码为零,并且 API 似乎假设在数据级别没有部分的概念。是否可以通过新的 Realm 过滤和更改通知支持以任何方式实现部分?
  • 这实际上很有帮助,因为文档对此并不明显。谢谢老哥
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-23
  • 1970-01-01
  • 1970-01-01
  • 2011-03-02
  • 2013-08-15
  • 1970-01-01
  • 2019-08-17
相关资源
最近更新 更多