我看过一些帖子建议在块中使用类似下面的内容来异步下载图像,以便在主线程上调用setNeedsDisplay
并让它更快地显示。
dispatch_async(main_queue, ^{
[view setNeedsDisplay];
});
我正在尝试这个,如下所示,但下载后图像不会显示。通常大约有4到5秒的延迟。我知道这一点,因为如果我选择任何特定行,则会显示图像,而其他行仍未显示。
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
UIImageView *iv = (UIImageView*)[cell viewWithTag:kCellSubViewWavImageView];;
//async for scroll performance
dispatch_queue_t queue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSURL *url = [[NSURL alloc] initWithString:[self.user.favWavformURLAr objectAtIndex:indexPath.row]];
NSLog(@"background");
NSData *imageData = [[NSData alloc] initWithContentsOfURL:url];
UIImage *image = [[UIImage alloc] initWithData:imageData];
iv.image = image;
dispatch_queue_t main_queue = dispatch_get_main_queue();
dispatch_async(main_queue, ^{
NSLog(@"main thread");
[iv setNeedsDisplay];
});
});
}
return cell;
}
顺便说一句,下面的NSLog(@"background");
和NSLog(@"main thread");
调用按照以下顺序打印,用于调用最初的6个单元格,这是我所期望的。但仍然无效:
2012-02-17 20:46:27.120 SoundcloudFavs[8836:1c03] background
2012-02-17 20:46:27.169 SoundcloudFavs[8836:1b03] background
2012-02-17 20:46:27.170 SoundcloudFavs[8836:6b07] background
2012-02-17 20:46:27.173 SoundcloudFavs[8836:7503] background
2012-02-17 20:46:27.174 SoundcloudFavs[8836:7103] background
2012-02-17 20:46:27.177 SoundcloudFavs[8836:8003] background
2012-02-17 20:46:27.219 SoundcloudFavs[8836:207] main thread
2012-02-17 20:46:27.270 SoundcloudFavs[8836:207] main thread
2012-02-17 20:46:27.282 SoundcloudFavs[8836:207] main thread
2012-02-17 20:46:27.285 SoundcloudFavs[8836:207] main thread
2012-02-17 20:46:27.296 SoundcloudFavs[8836:207] main thread
2012-02-17 20:46:27.300 SoundcloudFavs[8836:207] main thread
有什么想法吗?
答案 0 :(得分:3)
尝试在主线程中设置下载的图像。
dispatch_async(main_queue, ^{
NSLog(@"main thread");
iv.image = image;
});
最好将图像添加为不属于单元格的子视图,而是cell.contentView
。