Saturday, June 14, 2014

Loading and Caching Images in UITableViewCell

@interface ViewController : UIViewController
@property (strong ,nonatomic) NSMutableArray *tableItems;
@property (strong ,nonatomic) NSMutableDictionary *cachedImages;

@end


@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.cachedImages = [[NSMutableDictionary alloc] init];
    self.tableItems = [[NSMutableArray alloc] init];
    // Do any additional setup after loading the view, typically from a nib.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return self.tableitems.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
   
    if(cell == nil){
       
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifer];
    }

    NSString *identifier = [NSString stringWithFormat:@"Cell%d" ,
                            indexPath.row];
   
    if([self.cachedImages objectForKey:identifier] != nil){
        cell.imageView.image = [self.cachedImages valueForKey:identifier];
    }else{
       
        char const * s = [identifier  UTF8String];
       
        dispatch_queue_t queue = dispatch_queue_create(s, 0);
       
        dispatch_async(queue, ^{
           
            NSString *url = @"http://ovidos.com/img/logo.png";
           
            UIImage *img = nil;
           
            NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
           
            img = [[UIImage alloc] initWithData:data];
           
            dispatch_async(dispatch_get_main_queue(), ^{
               
                if ([tableView indexPathForCell:cell].row == indexPath.row) {
                   
                    [self.cachedImages setValue:img forKey:identifier];

                    cell.imageView.image = [self.cachedItems valueForKey:identifier];
                }
            });//end
        });//end
    }
   

    return cell;

}

@end

No comments: