gpt4 book ai didi

ios - 使用 UICollectionView 观察 Realm - 竞争条件

转载 作者:可可西里 更新时间:2023-11-01 01:57:05 25 4
gpt4 key购买 nike

我正在使用 Realm 作为缓存层,这样无论何时向用户呈现数据,它都会首先从数据库中获取并显示给用户。随后,发送服务器请求以获取最新版本的数据,将其与 Realm 数据库同步并在 UICollectionView 中显示更改。

问题是当从 Realm 数据库中检索缓存数据并且 UICollectionView 正在更新时,服务器更新请求有可能在此之前完成UICollectionView 加载了所有单元格,并且由于 Results 列表是实时数据集合,它可能已被修改。现在,例如,如果在服务器端删除了一个项目,则实时集合将减少一个项目,因此导致越界异常。

话虽这么说,考虑到 results 可以在 UITableView 逐行询问每一行:

class ViewController: UITableViewController {
var notificationToken: NotificationToken? = nil

override func viewDidLoad() {
super.viewDidLoad()
let realm = try! Realm()
let results = realm.objects(Person.self).filter("age > 5")

// Observe Results Notifications
notificationToken = results.observe { [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()
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()
case .error(let error):
// An error occurred while opening the Realm file on the background worker thread
fatalError("\(error)")
}
}
}

deinit {
notificationToken?.invalidate()
}
}

我能想到的解决这个问题的唯一方法是创建结果的深拷贝,并使用信号量或类似方法同步观察函数的主体,以确保数据不会处于不一致的状态,我考虑效率很低。 (请注意,tableView.endUpdates() 并不意味着 UITableView 已重新加载所有数据,但它只是被分派(dispatch)到队列并准备好进行异步处理。)

我想听听任何关于如何以有效方式实现这一点以消除上述竞争条件的建议。

最佳答案

您需要在主线程上完成所有 UI 更新。如果您执行此操作,第一组结果会更新主线程上的 Collection View ,当下一组结果也出现时,它将在主线程中排队,以便在第一组完成后更新。

关于ios - 使用 UICollectionView 观察 Realm - 竞争条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51598510/

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