使用块从后台线程加载图像

时间:2011-09-21 15:04:00

标签: iphone objective-c ipad

我有以下方法,它基本上调用请求在后台线程中加载图像的NSData数组:

[query findObjectsInBackgroundWithBlock:^(NSArray * objects, NSError * error){

}];

在这种情况下,objects是NSData的数组。问题是,如果我要加载100个图像(数组中有100个元素)。这意味着用户必须等待一段时间才能看到UITableView中出现的任何图像。我想要做的是让他们看到一个图像一旦可用/加载..我是否必须更改代码,以便它执行100个后台线程来加载图像?

3 个答案:

答案 0 :(得分:49)

你可以在你的cellForRowAtIndexPath中实现类似的东西:

这样你就可以在后台加载每个图像,加载后相应的单元格会在mainThread上更新。

      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void) {
        NSData *data0 = [NSData dataWithContentsOfURL:someURL];
        UIImage *image = [UIImage imageWithData:data0];

        dispatch_sync(dispatch_get_main_queue(), ^(void) {
            UIImageView* imageView = (UIImageView*)[cell viewWithTag:100];
            imageView.image = image;
        });
    });

答案 1 :(得分:1)

不,您不必创建那么多后台线程。使用NSOperationQueue

答案 2 :(得分:0)

您可以创建NSInvocationOperation并将其设置为NSOperationQueue

例如: 正在初始化NSOperationQueue

NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];

创建NSInvocationOperation后:

NSInvocationOperation* downloadOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(selectorToDownloadImage:) object:YouData];    
[operationQueue addOperation:downloadOperation];
[downloadOperation release];