Realm Swift回调函数
问题描述:
我使用swift3和Realm 2.3。Realm Swift回调函数
而且事务完成后我需要回调。
例如,我有一个代码如下,在领域数据事务完成后如何获得回调?
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()
}
答
这取决于您为什么需要回调,但有多种方式可以在数据更改时提供通知。
最常见的用例是当您显示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
}
}
领域对象的属性也是KVO-compliant,所以你也可以使用传统的苹果addObserver
API时跟踪特定属性的变化。
所有这些都失败了,如果您有一个非常具体的用例来通知Realm数据发生更改时,您还可以使用类似NotificationCenter
的类似方法来实现您自己的通知。
如果您需要任何额外的说明,请跟进。