我正在尝试在辅助线程上执行昂贵的操作,我是新手。所以在cellForRowAtIndexPath
我使用GCD来设计单元格并将其添加到contentView
。
我使用以下方法设计单元格
-(UIView *)designCellAtIndexPath:(NSIndexPath *)indexPath size:(CGSize)aSize
{
UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, aSize.width, aSize.height)];
....
//design the cell with lots of UI elements
....
return backView;
}
我曾在下面试过,但是电池在很长一段时间后(大约8-9秒)正在更新,但是3个日志立即在控制台中打印。
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
dispatch_queue_t backgroundQueue = dispatch_queue_create("threadToDesignCell", NULL);
dispatch_async(backgroundQueue, ^{
NSLog(@"queue interval1- %f", [[NSDate date] timeIntervalSince1970]);
UIView *cellContentView = [self designCellAtIndexPath:indexPath size:[cell frame].size];
NSLog(@"queue interval2- %f", [[NSDate date] timeIntervalSince1970]);
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"queue interval3- %f", [[NSDate date] timeIntervalSince1970]);
[[cell contentView] addSubview:cellContentView];
//[cell setNeedsDisplay];
});
});
我也曾在下面尝试,但同样的问题就像上面那样出现了。
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSLog(@"queue interval1- %f", [[NSDate date] timeIntervalSince1970]);
UIView *cellContentView = [self designCellAtIndexPath:indexPath size:[cell frame].size];
NSLog(@"queue interval2- %f", [[NSDate date] timeIntervalSince1970]);
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"queue interval3- %f", [[NSDate date] timeIntervalSince1970]);
[[cell contentView] addSubview:cellContentView];
//[cell setNeedsDisplay];
});
});
在日志中
2015-03-13 12:52:46.515 TableDesigner[2262:65363] queue interval1- 1426231366.515081
2015-03-13 12:52:46.609 TableDesigner[2262:65363] queue interval2- 1426231366.609620
2015-03-13 12:52:46.914 TableDesigner[2262:65326] queue interval3- 1426231366.914309
请帮助我理解这里究竟发生了什么错误。
答案 0 :(得分:0)
我跛行并宣称你的'designCellAtIndexPath'也访问UIKit - 其中99%不是线程安全的,应该只在主线程上完成。 :)
所以尝试这个毫无意义的代码,如果你没有遭受巨大的延迟,那就是它
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
UIView *cellContentView = [self designCellAtIndexPath:indexPath size:[cell frame].size ];
[[cell contentView] addSubview:cellContentView];
});
});