使用NSOperationQueue异步加载来自Web的多个图像

时间:2012-01-11 07:34:39

标签: iphone ios nsoperationqueue nsinvocationoperation

我有一个数组或网址,指向服务器上的图像。现在我想在滚动视图中显示图像,每行有4个图像。我正在考虑使用NSOperationQueue和NSInvocationOperation异步下载图像。我使用以下网址作为参考:
http://www.switchonthecode.com/tutorials/loading-images-asynchronously-on-iphone-using-nsinvocationoperation

但我不确定如何下载多张图片。我是否必须使用多个NSInvocationOperation对象运行for循环并将其添加到NSOperationQueue对象?

我正在寻找任何指导来完成我的任务。

修改 我做了以下但是NSOperationQueue无法调用NSInvocationOperation对象

NSOperationQueue *queue = [NSOperationQueue new];
for(int i = 0;i<rowcount;i++){
    for(int j =0; j<4;j++){
        UIButton *btnAlbum = [[UIButton alloc] initWithFrame:CGRectMake(x, y, 72, 72)];
        [btnAlbum setBackgroundImage:[UIImage imageNamed:@"placeHolder.png"] forState:UIControlStateNormal];
        btnAlbum.tag = count+100;
        //[btnAlbum addTarget:self action:@selector(viewAlbum:) forControlEvents:UIControlEventTouchUpInside];
        [scrlvw addSubview:btnAlbum];
        //[btnAlbum release];
        x = x + 80;
        count++;

        NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
                                            initWithTarget:self
                                            selector:@selector(loadImage) 
                                            object:nil];

        [queue addOperation:operation]; 
        [operation release];
    }
    x = 0;
    y = y +80;
}

感谢
的Pankaj

3 个答案:

答案 0 :(得分:1)

是 - 对于您要下载的每个图像,您创建一个NSInvocationOperation,在执行时将调用下载图像的例程。 NSInvocationOperation被添加到队列中,该队列负责在其自己的线程上执行NSInvocationOperation。

您只需要一个队列,但每次下载都需要一个新的NSInvocationOperation。

答案 1 :(得分:1)

ASIHTTPRequest来救我,我能够轻松完成任务。

答案 2 :(得分:0)

为什么不使用块和Grand Central Dispatch来加载这些图像?查看this post,看看这是否适合您。