Reputation: 13090
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....
Upvotes: 2
Views: 4904
Reputation: 4207
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
}
Upvotes: 0
Reputation: 4912
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.
Upvotes: 5