【发布时间】:2012-04-11 17:24:20
【问题描述】:
在创建单元格时,我正在做一些繁重的计算。我试图找出保持 UITableView 流畅的最佳方法,但在同一类型的背景下进行计算(保持 UI 线程没有太多处理)。
仅出于测试目的,我将其用作我的繁重计算方法:
+(NSString*)bigCalculation
{
int finalValue=0;
int j=0;
int i=0;
for (i=0; i<1000; i++) {
for (j=0; j<10000000; j++) {
j++;
}
finalValue+=j/100*i;
}
return [NSString stringWithFormat:@"%d",finalValue];
}
在 cellForRowAtIndexPath 内部,我只做以下事情:
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier=@"identifier";
UITableViewCell *cell=nil;
cell=[aTableView dequeueReusableCellWithIdentifier:identifier];
if(!cell)
{
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
}
NSString *text=[dataSource objectForKey:[[dataSource allKeys] objectAtIndex:indexPath.row]];
dispatch_queue_t a_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
;
dispatch_async(a_queue, ^{
NSString *subtitle=[CalculationEngine bigCalculation];
dispatch_async(dispatch_get_main_queue(), ^{
[[cell detailTextLabel] setText:subtitle];
dispatch_release(a_queue);
});
});
[[cell textLabel] setText:text];
return cell;
}
目前我有 UITableView 流体,而在后台一切正常。所以我的问题是:
1)这是实现我想要的最佳方式吗?KVO 也可以作为答案吗?
2) 在此之前:
dispatch_queue_t a_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
我在做:
dispatch_queue_create("com.mydomain.app.newimagesinbackground", DISPATCH_QUEUE_SERIAL)
而且性能很差。你能解释一下为什么吗?
【问题讨论】:
-
您是为每个单元创建一个新的串行队列还是在它们之间共享一个。我假设您了解将所有任务安排在同一个串行队列上的含义。
-
另外,由于您不拥有全局队列,因此您没有义务释放它。 dispatch_release(a_queue) 将被忽略。
-
此外,由于该块包含对队列的引用,您可以在提交工作后立即释放它。
-
嗨 pingbat,现在我知道了。我确实很难理解。 :P(根据 Instruments,296 个线程正在运行)
-
因此,我怀疑两者的总体执行时间都差不多。通过使用并发队列,您将更快地返回第一个结果,因为调度程序将对一次执行的块数设置限制。使用许多串行队列可能会导致所有块同时运行(如果您滚动整个 TableView)。这会让您等待很长时间,然后突然间所有结果都会在大致相同的时间出现。这听起来像你看到的行为吗?
标签: iphone ios multithreading concurrency grand-central-dispatch