从文件异步加载图像
问题描述:
我在本地存储中有一个相对的图像,我想在不干扰UI线程的情况下将其显示给用户。 我正在使用从文件异步加载图像
[[UIImage alloc] initWithContentsOfFile:path];
加载图像。
任何建议/帮助,请....
答
如果你正在试图做的是保持UI线程所有可用的,完成后成立了一个简短的方法来加载它在后台更新ImageView的:
-(void)backgroundLoadImageFromPath:(NSString*)path {
UIImage *newImage = [UIImage imageWithContentsOfFile:path];
[myImageView performSelectorOnMainThread:@selector(setImage:) withObject:newImage waitUntilDone:YES];
}
这假设myImageView
是该类的成员变量。现在,只需在后台从任何线程中运行它:
[self performSelectorInBackground:@selector(backgroundLoadImageFromPath:) withObject:path];
注意,在backgroundLoadImageFromPath
则需要等到setImage:
选择完成,否则后台线程的自动释放池可以解除分配图像前setImage:
方法可以保留它。
答
您可以使用NSInvocationOperation用于此目的: 呼叫
NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc]
initWithTarget:self
selector:@selector(loadImage:)
object:imagePath];
[queue addOperation:operation];
其中:HTTP:
- (void)loadImage:(NSString *)path
{
NSData* imageFileData = [[NSData alloc] initWithContentsOfFile:path];
UIImage* image = [[UIImage alloc] initWithData:imageFileData];
[self performSelectorOnMainThread:@selector(displayImage:) withObject:image waitUntilDone:NO];
}
- (void)displayImage:(UIImage *)image
{
[imageView setImage:image]; //UIImageView
}
可以异步通过遵循这个问题的答案所描述的方法加载图像数据: //*.com/questions/3111543 – Greg 2010-10-18 16:52:52