and*_*ius 2 iphone objective-c uiimage
我正在制作一个应用程序,允许您浏览网站上的图片.我目前正在使用以下方式下载图像:
UIImage *myImage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];
Run Code Online (Sandbox Code Playgroud)
这很好用,但可能很耗时.我开始下载20张图片,但是直到30秒左右下载所有图片之后我才能做任何事情.
这一次等待并不是那么糟糕,但如果我想下载第二十四张图像,我将不得不再等30秒.
基本上,有没有一种方法可以一次下载这些图像而不需要保留任何动画?
谢谢.
当然,将下载任务放在一个线程中,并使用回调让您的程序知道每个图像何时完成.然后,您可以在完成加载时绘制图像,而不是占用应用程序的其余部分. 此链接有一个模板,您可以将其用作示例.
这是一个快速而肮脏的例子:
- (void)downloadWorker:(NSString *)urlString
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [[UIImage alloc] initWithData:data];
[self performSelectorOnMainThread:@selector(imageLoaded:)
withObject:image
waitUntilDone:YES];
[image release];
[pool drain];
}
- (void)downloadImageOnThread:(NSString *)url
{
[NSThread detachNewThreadSelector:@selector(downloadWorker:)
toTarget:self
withObject:url];
}
- (void)imageLoaded:(UIImage *)image
{
// get the image into the UI
}
Run Code Online (Sandbox Code Playgroud)
调用downloadImageOnThread你想要加载的每个图像,每个图像都会得到自己的线程,并且每个图像都会被调用imageLoaded.