我使用 swift3 和 Realm 2.3。
交易完成后我需要回调。
例如,我有如下代码,如何在领域数据事务完成后获得回调?
DispatchQueue.main.async {
try! self.realm.write {
self.realm.add(friendInfo, update: true)
}
}
我使用 swift3 和 Realm 2.3。
交易完成后我需要回调。
例如,我有如下代码,如何在领域数据事务完成后获得回调?
DispatchQueue.main.async {
try! self.realm.write {
self.realm.add(friendInfo, update: true)
}
}
事务是同步执行的。因此,您可以在执行事务后立即执行代码。
DispatchQueue.main.async {
try! self.realm.write {
self.realm.add(friendInfo, update: true)
}
callbackFunction()
}
这取决于您为什么需要回调,但 Realm 可以通过多种方式在数据更改时提供通知。
最常见的用例是当您显示Results
对象中的项目列表时。在这种情况下,您可以使用Realm 的更改通知功能来更新特定对象:
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 兼容的,因此您还可以使用传统的 Apple addObserver
API 来跟踪特定属性何时发生变化。
如果所有这些都失败了,如果您有一个非常具体的用例来通知 Realm 数据何时发生更改,您还可以使用类似NotificationCenter
.
如果您需要任何其他说明,请跟进。