从文件异步加载图像

时间:2010-10-18 16:40:14

标签: iphone objective-c asynchronous ios4

我在本地存储中有一个相对的图像,我想在不干扰UI线程的情况下向用户显示它。 我正在使用

[[UIImage alloc] initWithContentsOfFile:path];

加载图片。

任何建议/帮助请....

2 个答案:

答案 0 :(得分:5)

如果您要做的就是保持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:方法保留它之前解除分配图像。

答案 1 :(得分:0)

您可以将NSInvocationOperation用于此目的: 呼叫

NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc]
                                    initWithTarget:self
                                    selector:@selector(loadImage:)
                                    object:imagePath];
[queue addOperation:operation];

其中:

- (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
}