NOTE: I am using ARC
I have a lazy image loading technique that works brilliantly when loading images from a web url. However, I am having problems loading images from core data. Here is the method I am using:
I first alloc init my mutable arrays, load my data from core data and then store it in an array. Then I have this code:
NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc]
initWithTarget:self
selector:@selector(loadImage)
object:nil];
[queue addOperation:operation];
And then...
- (void)loadImage {
for (int i = 0; i < [myArrayFromCoreData count]; i++) {
AnObject *myObject = [myArrayFromCoreData objectAtIndex:i];
UIImage* image;
if ([myObject.image length] == 0) {
image = [UIImage imageNamed:@"default.png"];
}
else {
image = [[UIImage alloc] initWithData:myObject.image];
}
[self performSelectorOnMainThread:@selector(displayImage:) withObject:[NSArray arrayWithObjects:image,myObject.myObjectId, nil] waitUntilDone:NO];
}
}
- (void)displayImage:(NSArray*)array {
[loadedImages setObject:[array objectAtIndex:0] forKey:[array objectAtIndex:1]];
[self.myTable reloadData];
}
Up to here there is no lag and an NSLog shows that all my images are added to the myObjectLoadedImages array.
The problem I am having is there is a lag when scrolling the table view and it is sometimes causing a crash. Here is the code I am using to display the loaded images:
UIImage* image = [loadedImages objectForKey:myObject.myObjectId];
if (image != NULL) {
myImageView.image = image;
}
else {
myImageView.image = [UIImage imageNamed:@"default.png"];
}
This is in the cellForRowAtIndexPath
method so it is being called every time the cell is displayed. Is there something I am doing wrong here as my code is adapted from a class which is working fine loading images from a web url.