创建单元格时,我正在做一些繁重的计算。我试图找出保持 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)
而且表现很差。你能解释一下为什么吗?