使用块或NSOperation加载Image?

时间:2011-05-11 14:17:29

标签: ios multithreading objective-c-blocks nsoperation grand-central-dispatch

我需要知道是否最好使用NSOperation或Block将大量图像加载到UIScrollView中?我创建了所有的Imageview并将每个UIImageView放在正确的位置进入滚动。

为避免内存警告,我选择一次加载图像。我的想法是创建一种队列并插入要加载到队列中的所有图像。我必须使用block或NSOperation来做这个吗?

2 个答案:

答案 0 :(得分:5)

tableView:cellForRowAtIndexPath:中,您可以使用GCD(Grand Central Dispatch)异步加载图像。

像这样:

static NSString *CellIdentifier = @"ImageCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                   reuseIdentifier:CellIdentifier] autorelease];
}
NSString *imagepath = //get path to image here
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    dispatch_sync(dispatch_get_main_queue(), ^{
        [[cell imageView] setImage:image];
        [cell setNeedsLayout];
    });
});
return cell;

编辑:要获得更好的答案,请观看WWDC '12 Session 211 - “在iOS上构建并发用户界面”(感谢@ sc0rp10n!)

答案 1 :(得分:2)

如果你想要一个队列,那么NSOperationQueue(以及NSOperations)是一个明智的选择:)