为什么在它之后调用 scrollToRow 时重新加载数据会导致崩溃?
Why reload data causes crash when scrollToRow is called after it?
重新加载数据导致在其后调用 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不仅依赖于运行主线程,还依赖于主队列,检查当前队列比检查当前线程更安全。
重新加载数据导致在其后调用 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不仅依赖于运行主线程,还依赖于主队列,检查当前队列比检查当前线程更安全。