- Best way to cache images on ios app?
- @interface FirstViewController : UITableViewController{
- /**/
- NSCache *_imageCache;
- }
- - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- {
- static NSString *CellIdentifier = @"hallo";
- CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
- if (cell == nil)
- {
- cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
- }
- NSMutableArray *marr = [hallo objectAtIndex:indexPath.section];
- NSDictionary *dict = [marr objectAtIndex:indexPath.row];
- NSString* imageName = [dict objectForKey:@"Image"];
- //NSLog(@"url: %@", imageURL);
- UIImage *image = [_imageCache objectForKey:imageName];
- if(image)
- {
- cell.imageView.image = image;
- }
- else
- {
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- NSString* imageURLString = [NSString stringWithFormat:@"example.com/%@", imageName];
- NSURL *imageURL = [NSURL URLWithString:imageURLString];
- UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:imageURL]];
- if(image)
- {
- dispatch_async(dispatch_get_main_queue(), ^{
- CustomCell *cell =(CustomCell*)[self.tableView cellForRowAtIndexPath:indexPath];
- if(cell)
- {
- cell.imageView.image = image;
- }
- });
- [_imageCache setObject:image forKey:imageName];
- }
- });
- }
- cell.textLabel.text = [dict objectForKey:@"Name"];
- return cell;
- }
- - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- {
- static NSString *CellIdentifier = @"ilvcCell";
- UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
- // set the various cell properties
- // now update the cell image
- NSString *imagename = [self imageFilename:indexPath]; // the name of the image being retrieved
- UIImage *image = [_imageCache objectForKey:imagename];
- if (image)
- {
- // if we have an cachedImage sitting in memory already, then use it
- cell.imageView.image = image;
- }
- else
- {
- cell.imageView.image = [UIView imageNamed:@"blank_cell_image.png"];
- // the get the image in the background
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- // get the UIImage
- UIImage *image = [self getImage:imagename];
- // if we found it, then update UI
- if (image)
- {
- dispatch_async(dispatch_get_main_queue(), ^{
- // if the cell is visible, then set the image
- UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
- if (cell)
- cell.imageView.image = image;
- });
- [_imageCache setObject:image forKey:imagename];
- }
- });
- }
- return cell;
- }