使用块或NSOperation加载Image?

Pab*_*ect 2 multithreading nsoperation grand-central-dispatch ios objective-c-blocks

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

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

sud*_*-rf 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;
Run Code Online (Sandbox Code Playgroud)

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