我已经看到一些帖子建议在块内使用类似以下的内容异步下载图像,以便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");
andNSLog(@"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
有任何想法吗?