Swift 域通知不会针对初始值触发

Swift 域通知不会针对初始值触发,swift,realm,Swift,Realm,我以如下方式将观察者附加到对象 let user = realm.object(ofType: User.self, forPrimaryKey: uid) userNotificationToken = user.observe({ change in // Update UI }) 我希望观察块在初始值和更新时都会触发。但它只会在更新时触发。领域通知是这样工作的吗?我在我的项目中使用了下面的领域通知,在这两种情况下都适用 步骤1:如下声明N

我以如下方式将观察者附加到对象

let user = realm.object(ofType: User.self, forPrimaryKey: uid)

userNotificationToken = user.observe({ change in
        // Update UI            
    })

我希望观察块在初始值和更新时都会触发。但它只会在更新时触发。领域通知是这样工作的吗?

我在我的项目中使用了下面的
领域通知
,在这两种情况下都适用

步骤1:如下声明NotificationToken

var notificationToken: NotificationToken? = nil
第二步:这里是it的主要实现

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()
}
更新

注意:如果是单个对象,观察块将仅在对象更改时触发(更改、删除、错误)

有关更多信息,请参阅领域官方文件关于

要在最初更新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.
}

希望对你有帮助快乐编码

你好,Jakir。它似乎适用于您的示例中的集合类型,但不适用于单个集合objects@NezihYılmaz如果我的答案对您有用,那么请将此答案向上投票,以便其他用户获得有用的答案。谢谢