ios开发:如何加载大量图片 相册示例

本文介绍如何使用NSOperationQueue实现iOS应用中500张图片的后台批量下载,并通过NSInvocationOperation进行任务调度。同时,文章提供了详细的代码示例,包括图片加载、显示等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Create a NSOperationQueue to handle background downloading.

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

2. Now create an NSInvocationOperation for each image that you want to download and add it to operationQueue.

int noOfImages = 500;
for(int i = 0; i  noOfImages; i++)
{
NSInvocationOperation *invocationOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(loadDataAsychn:) object:i];
[queue addOperation:invocationOperation];
[operation release];
}

In this code, we have created an operation calling loadDataAsynchn: method which is to be implemented and added to queue. After adding created operation to the queue, it will do the rest of the downloading work for your app. You can add more operations to the same queue to be performed later.

Now we will implement loadDataAsychn method.

3. Implement loadDataAsychn method for loading data from the given URL, creating an image and setting it to desired placeholder.

-(void)loadDataAsychn:(NSString*)imageNo
{
NSString *imgStr = [NSString stringWithFormat:@"http://192.168.0.163/Test/images/%@.jpg",imageNo];
NSData *imageData=[[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:imgStr]];
UIImage *image=[[UIImage alloc]initWithData:imageData];
[imgDict setValue:image forKey:@"image"];
[imgDict setValue:imageNo forKey:@"imageNo"];
[self performSelectorOnMainThread:@selector(showImg:) withObject:imgDict waitUntilDone:NO];
}

The loadDataAsychn method is used to download the information from a given URL and creating an image with downloaded data. As we all know that none of the UI related methods can be performed on background thread. So, in loadDataAsychn method, we call showImage method on the main thread to display images.

4. We will now implement showImage which is responsible for updating UI.

(void)showImage:(NSMutableDictionary *)Dict
{
int i = [[Dict objectForKey:@"imageNo"] intValue];
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(320*(i-1), 0, 320, 460)];
[imgView setImage:[Dict objectForKey:@"image"]];
[myScrollView addSubview:imgView];
}

In this method, we create an UIImageView for displaying image, setting image on it and adding it to scroll-view dynamically.

官方的相册程序示例  http://developer.apple.com/library/ios/#samplecode/PhotoScroller/Introduction/Intro.html#//apple_ref/doc/uid/DTS40010080-Intro-DontLinkElementID_2

转载于:https://www.cnblogs.com/xiongqiangcs/archive/2013/06/13/3134486.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值