Realm Swift callback function

2019-07-10 02:49发布

问题:

I use swift3 and Realm 2.3.

And I need callback after transaction is finished.

for example, I have a code as below, how can I get call back after a realm data transaction is finished ?

DispatchQueue.main.async {

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

}

回答1:

Transactions are executed synchronously. So you can just perform the code right after you execute the transaction.

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

    callbackFunction()
}


回答2:

It depends on why you need the callback, but there are a variety of ways Realm can provide a notification when data is changed.

The most common use-case is when you're displaying a list of items from a Results object. In that case, you can use Realm's change notifications feature to update specific objects:

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 object properties are also KVO-compliant, so you can also use the traditional Apple addObserver API to track when a specific property changes.

Failing all of that, if you have a very specific use-case for being notified of when a piece of Realm data changes, you can also implement your own notifications using something like NotificationCenter.

Please follow-up if you need any additional clarification.