Load image asynchronously from file

2019-04-01 05:07发布

I have an relatively image in local storage, I want to show it to the user without disturbing UI thread. I'm currently using

[[UIImage alloc] initWithContentsOfFile:path];

to load image.

Any suggestions/help please....

2条回答
聊天终结者
2楼-- · 2019-04-01 05:32

If all you're trying to do is keep the UI thread available, set up a short method to load it in the background and update the imageView when done:

-(void)backgroundLoadImageFromPath:(NSString*)path {
    UIImage *newImage = [UIImage imageWithContentsOfFile:path];
    [myImageView performSelectorOnMainThread:@selector(setImage:) withObject:newImage waitUntilDone:YES];
}

This presumes myImageView is a member variable of the class. Now, simply run it in the background from any thread:

[self performSelectorInBackground:@selector(backgroundLoadImageFromPath:) withObject:path];

Note, in backgroundLoadImageFromPath you need to wait until the setImage: selector finishes, otherwise the background thread's autorelease pool may deallocate the image before the setImage: method can retain it.

查看更多
何必那么认真
3楼-- · 2019-04-01 05:34

You can use NSInvocationOperation for this purpose: Call

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

Where:

- (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
}
查看更多
登录 后发表回答