【问题标题】:Realm Swift callback function领域 Swift 回调函数
【发布时间】:2017-01-23 02:12:50
【问题描述】:

我使用 swift3 和 Realm 2.3。

交易完成后我需要回调。

例如,我有如下代码,如何在领域数据交易完成后回调?

DispatchQueue.main.async {

     try! self.realm.write {
          self.realm.add(friendInfo, update: true)
     }

}

【问题讨论】:

    标签: swift3 realm realm-mobile-platform


    【解决方案1】:

    事务是同步执行的。因此,您可以在执行事务后立即执行代码。

    DispatchQueue.main.async {
        try! self.realm.write {
            self.realm.add(friendInfo, update: true)
        }
    
        callbackFunction()
    }
    

    【讨论】:

      【解决方案2】:

      这取决于您为什么需要回调,但 Realm 可以通过多种方式在数据更改时提供通知。

      最常见的用例是当您显示来自Results 对象的项目列表时。在这种情况下,您可以使用Realm's change notifications 功能来更新特定对象:

      let realm = try! Realm()
      let results = realm.objects(Person.self).filter("age > 5")
      
      // 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.insertRows(at: insertions.map({ IndexPath(row: $0, section: 0) }),
                             with: .automatic)
          tableView.deleteRows(at: deletions.map({ IndexPath(row: $0, section: 0)}),
                             with: .automatic)
          tableView.reloadRows(at: modifications.map({ IndexPath(row: $0, section: 0) }),
                             with: .automatic)
          tableView.endUpdates()
          break
        case .error(let error):
          // An error occurred while opening the Realm file on the background worker thread
          fatalError("\(error)")
          break
        }
      }
      

      Realm 对象属性也是KVO-compliant,因此您也可以使用传统的 Apple addObserver API 来跟踪特定属性何时发生变化。

      如果所有这些都失败了,如果您有一个非常具体的用例可以在某段 Realm 数据更改时收到通知,您还可以使用 NotificationCenter 之类的方式实现自己的通知。

      如果您需要任何其他说明,请跟进。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多