【问题标题】:Realm notification does not fire for the initial value初始值不会触发领域通知
【发布时间】:2019-09-08 21:43:44
【问题描述】:

我按照以下方式将观察者附加到对象上

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

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

而且我希望观察块在初始值和更新上都触发。然而,它只会在更新时触发。领域通知是否以这种方式工作?

【问题讨论】:

    标签: swift realm


    【解决方案1】:

    我在我的项目中使用了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.
    }
    

    【讨论】:

    • 嗨,Jakir。它似乎适用于您的示例中的集合类型,但不适用于单个对象
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    相关资源
    最近更新 更多