ios - 为什么在调用scrollToRow时重新加载数据会导致崩溃?

标签 ios swift uitableview reloaddata

在重新加载数据后调用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/

相关文章:

iphone - 保留日期格式以修复iPhone SDK

php - IOS中的推送通知-握手失败

ios - 带有图像的 UITableView 在滚动时会暂时显示错误的图像

ios - 对齐来自 Swift 3 中不同单元格的按钮

java - 如何仅在尚未上传的情况下将文件上传到 S3?

ios - AVAssetResourceLoaderDelegate 和 HLS 不起作用?

ios - 在 SwiftUI 中监听 AVPlayer timeControlStatus 的变化

ios - 使用多个自定义 UITableViewCells

ios - 单击时 MapView 自定义图钉不显示详细信息

ios - 在 Swift 3 中按字母顺序对 Realm 对象排序