我使用swift3和Realm 2.3。Realm Swift回調函數
而且事務完成後我需要回調。
例如,我有一個代碼如下,在領域數據事務完成後如何獲得回調?
DispatchQueue.main.async {
try! self.realm.write {
self.realm.add(friendInfo, update: true)
}
}
我使用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
的類似方法來實現您自己的通知。
如果您需要任何額外的說明,請跟進。