Reputation: 8225
After two days searching this answer I found a solution.
I found the solution explained here by Duncan C:
How to implement:
- (void)viewDidLoad
{
(...)
dispatch_queue_t mainQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
imagesDictionary = [[NSMutableDictionary alloc] init];
(...)
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
(...)
NSData *imageData = [imagesDictionary objectForKey:@"IMAGE URL"];
if (imageData)
{
UIImage* image = [[UIImage alloc] initWithData:imageData];
imageFlag.image = image;
NSLog(@" Reatriving ImageData...: %@", @"IMAGE URL");
}
else
{
dispatch_async(mainQueue, ^(void) {
NSString *url = @"IMAGE URL";
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
imageFlag.image = image;
[imagesDictionary setObject:imageData forKey:@"IMAGE URL"];
NSLog(@" Downloading Image...: %@", @"IMAGE URL");
});
}
(...)
}
The project in GitHub: https://github.com/GabrielMassana/AsynchronousV2.git
I know that if the project is large and with a lot of cells I can go run out of memory. But I think this solution is a nice approach for a newbie.
What do you think about the project? If the project is really large, the best option is to save the images in disk? But then the problem is the possibility to go run out of memory in the disk, isn't it? Maybe, then, we need a mechanism to delete all the images from disk.
Upvotes: 3
Views: 1266
Reputation: 119242
Use NSCache to hold your downloaded images instead of NSDictionary. This will manage itself in low memory situations and remove items that haven't been accessed for a while. In that situation, they will be loaded from the URL again if needed.
Upvotes: 4