gpt4 book ai didi

ios - 为什么 tableview 数据源没有从 Realm Collection 观察者中改变?

转载 作者:行者123 更新时间:2023-11-30 11:05:51 26 4
gpt4 key购买 nike

我有对 Realm 数据库的请求

  func allContacts() -> Results<RMContact> {
let realm = self.encryptedRealm()
return realm!.objects(RMContact.self).sorted(byKeyPath: "lastActive", ascending: false)
}

以及演示者的代码

        DispatchQueue.main.async {
let contacts = RMContactsManager.shared.allContacts()
self.notificationToken = contacts.observe { [weak self] (changes: RealmCollectionChange) in
guard let tableView = self?.view.tableView else { return }
switch changes {
case .initial:
UIView.performWithoutAnimation {
tableView.reloadData()
}
case .update(_, let deletions, let insertions, let modifications):
UIView.performWithoutAnimation {
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()
}
case .error(let error):
fatalError("\(error)")
}
}
}

在 TableView 中设置新的lastActive值序列后没有改变对于 Controller 来说,排序是第一次实际进行,但在为 lastActive 属性设置新值后没有任何变化。是观察者问题吗?

最佳答案

问题似乎是您在插入、删除和修改方面发生了变化。

如果您首先执行插入然后删除(这就是您现在正在做的事情),它将插入新值并且数据源将被修改,因此现在当您删除行时,它将不正确。

此外,在您对数组进行排序的情况下,通常会替换两个元素,一个被删除,另一个将被添加。

所以可以解决你的问题的是,先删除,再插入。像这样:

UIView.performWithoutAnimation {
tableView.beginUpdates()
tableView.deleteRows(at: deletions.map({ IndexPath(row: $0, section: 0)}), with: .automatic)
tableView.insertRows(at: insertions.map({ IndexPath(row: $0, section: 0) }), with: .automatic)
tableView.reloadRows(at: modifications.map({ IndexPath(row: $0, section: 0) }), with: .automatic)
tableView.endUpdates()
}

关于ios - 为什么 tableview 数据源没有从 Realm Collection 观察者中改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52739266/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com