在重新加载数据后调用scrollToRow 时会导致崩溃。我必须在 DispatchQueue.main.async
中编写此代码,但是,为什么?
为什么我应该说当我已经在主队列中时切换到主队列?
self.tableView.reloadData()
print(Thread.current). // It is main
self.tableView.scrollToRow(at: indexPathToScroll, at: .top, animated: false)
print(Thread.current). // It is main
错误是:
_contentOffsetForScrollingToRowAtIndexPath:atScrollPosition:usingPresentationValues:]: row (20) beyond bounds (20) for section (0).
问题是这样解决的:
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
print(Thread.current). // It is main
self.tableView.scrollToRow(at: indexPathToScroll, at: .top, animated: false)
print(Thread.current). // It is main
})
当我在第一个代码中打印时,它是在主线程中运行的。为什么 DispatchQueue.main.async 会有所不同?
最佳答案
我找到的最简单的答案来自 GCD Main queue vs Main thread
While every app will ever only have one main thread, it is possible for many different queues to execute on this one main thread.
某些 API 不仅依赖于在主线程上运行,还依赖于主队列,检查当前队列比检查当前线程更安全。
关于ios - 为什么在调用scrollToRow时重新加载数据会导致崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50772304/