heightForRowAtIndexPath 中的线程问题
Threading issue in heightForRowAtIndexPath
我在 iOS 应用程序中遇到线程问题。这是一个已经发展了几年的大型应用程序。 (我是这个项目的许多贡献者之一,并且只对它的某些部分有深刻的理解)。
在某些情况下,应用会进行后台刷新,从而触发 tableview 委托方法。有时这会导致以下异常:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Only run on the main thread!'
我已经深入研究了这个问题,并确定在后台刷新期间,有些情况下不会从主线程调用 tableview 委托方法。
因此,我可以在 heightForRowAtIndexPath 内部检查我是否在主线程上。
如果不在主线程上,我可以调用 performSelectorOnMainThread 来尝试获取单元格高度,唯一的问题是选择器 returns 之前的 heightForRowAtIndexPath returns,所以我的单元格高度将为零。所以,这是 'chicken before the egg' 的情况。如何强制调用 heightForRowAtIndexPath 中的主线程并确保在 performSelectorOnMainThread 完成之前它不会 return?或者这甚至可能吗?谢谢!
您可以为此使用 GCD 实现后台线程,您无需手动管理 data.GCD 将为您执行所有操作。
Here is a piece of code
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//// DO some Background Processing Like Data Fetching
dispatch_async(dispatch_get_main_queue(), ^{
// Do some UIUpdates in your case call TableView Datasource
[yourtable reloaddata];
});
});
Swift:
DispatchQueue.global(qos: .default).async {
//// Do background tasks Like Data Fetching
DispatchQueue.main.async {
// do UI related tasks
}
}
问题不在于 heightForRowAtIndexPath,似乎您正在后台线程中重新加载 tableview。
尝试这样做
[self.tableview performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
我在 iOS 应用程序中遇到线程问题。这是一个已经发展了几年的大型应用程序。 (我是这个项目的许多贡献者之一,并且只对它的某些部分有深刻的理解)。
在某些情况下,应用会进行后台刷新,从而触发 tableview 委托方法。有时这会导致以下异常:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Only run on the main thread!'
我已经深入研究了这个问题,并确定在后台刷新期间,有些情况下不会从主线程调用 tableview 委托方法。
因此,我可以在 heightForRowAtIndexPath 内部检查我是否在主线程上。
如果不在主线程上,我可以调用 performSelectorOnMainThread 来尝试获取单元格高度,唯一的问题是选择器 returns 之前的 heightForRowAtIndexPath returns,所以我的单元格高度将为零。所以,这是 'chicken before the egg' 的情况。如何强制调用 heightForRowAtIndexPath 中的主线程并确保在 performSelectorOnMainThread 完成之前它不会 return?或者这甚至可能吗?谢谢!
您可以为此使用 GCD 实现后台线程,您无需手动管理 data.GCD 将为您执行所有操作。
Here is a piece of code
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//// DO some Background Processing Like Data Fetching
dispatch_async(dispatch_get_main_queue(), ^{
// Do some UIUpdates in your case call TableView Datasource
[yourtable reloaddata];
});
});
Swift:
DispatchQueue.global(qos: .default).async {
//// Do background tasks Like Data Fetching
DispatchQueue.main.async {
// do UI related tasks
}
}
问题不在于 heightForRowAtIndexPath,似乎您正在后台线程中重新加载 tableview。 尝试这样做
[self.tableview performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];