I suspect that the incorrect images that you see are the result of not setting the image of your place owner in case you have a local copy of the image, but still extract the local copy asynchronously. Also in the code added to download the local copy, you use the UIImage a UIKit in the background thread.
It is also interesting that you are doing some kind of caching of UIImage . Adding images to what I am assuming is an NSMutableArray property called imageFriends . But you seem to have commented on adding a cache in case you have a local copy of the file. Also your published code never uses cached UIImages .
While the 2 levels of caching seem a bit overpriced, if you want to do this, you can do something like this:
UIImage *userImage = [self.imageFriends objectForKey:[NSNumber numberWithInt:user.userId]]; if (userImage) { // if the dictionary of images has it just display it cell.imageView.image = userImage; } else { cell.imageView.image = [UIImage imageNamed:@"xger86x.jpg"]; // set placeholder image BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:user.image]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSData *imageData = nil; if (fileExists){ imageData = [NSData dataWithContentsOfFile:user.image]; } else { imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:user.imageURL]]; [imageData writeToFile:user.image atomically:YES]; } if (imageData){ dispatch_async(dispatch_get_main_queue(), ^{ // UIKit, which includes UIImage warns about not being thread safe // So we switch to main thread to instantiate image UIImage *image = [UIImage imageWithData:imageData]; [self.imageFriends setObject:image forKey:[NSNumber numberWithInt:user.userId]]; UITableViewCell *lookedUpCell = [tableView cellForRowAtIndexPath:indexPath]; if (lookedUpCell){ lookedUpCell.imageView.image = image; [lookedUpCell setNeedsLayout]; } }); } }); }
UIImage are part of UIKit and are not thread safe. But you can load NSData into another stream.
Njones
source share