我在我的项目中使用了Realm notification,如下所示,它在两种情况下都适用。
第 1 步: 像这样声明 NotificationToken。
var notificationToken: NotificationToken? = nil
Step-2:这里主要实现吧。
func getChatLogsFromLocalDB(){
messages = realm.objects(MessageDB.self).filter("contactId = '\(contactId)'" )
notificationToken = messages.observe{ [weak self](change: RealmCollectionChange) in
guard let tableview = self?.collectionView else {return}
switch(change){
case .initial:
tableview.reloadData()
print("initial....")
break
case .update(_, let deletions,let insertions,let modifications):
print("update....)")
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()
self!.updateUI()
break
case .error(let error):
print("Error in Realm Observer: \(error.localizedDescription)")
break
}
}
}
第 3 步: 使通知令牌无效
deinit {
notificationToken?.invalidate()
}
更新
注意:如果是单个对象,观察块只会在 ObjectChange(change,deleted,error) 时触发。
更多信息请参见领域官方文档
object-notifications
最初要更新 UI,可以按照这种方式进行。
let user = realm.object(ofType: User.self, forPrimaryKey: uid)
updateUI(user) // initially update the UI
userNotificationToken = user.observe({ change in
updateUI(user) // this block will only tigger when object will update
})
func updateUI(user: User){
// implement your UI update logic here.
}