gpt4 book ai didi

swift - 防止在 Realm 通知 block 中使用弱/无主 self 保留循环

转载 作者:行者123 更新时间:2023-11-28 14:53:22 25 4
gpt4 key购买 nike

我不确定我是否正确地掌握了闭包中无主/弱的概念,但我一直在阅读 RealmSwift 文档并想问为什么 https://realm.io/docs/swift/latest/#interface-driven-writes 中的示例代码|没有实现 weak self

token = collection.observe { changes in
switch changes {
case .initial:
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):
// handle error
()
}
}

但是https://realm.io/docs/swift/latest/#object-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)")
}
}

最佳答案

第一个例子没有使用weak/unowned,因为没有使用self.。但第二个例子包含:

guard let tableView = self?.tableView else { return }

因此,在这种情况下,您应该使用 weak/unowned,因为您在闭包中捕获了 self

关于swift - 防止在 Realm 通知 block 中使用弱/无主 self 保留循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49623828/

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