I would like to save images into the cache in TableViewcontroller. I wrote the following code, but cacheImage is always nil.
@property (nonatomic,strong)NSCache *imageCache;
@synthesize imageCache;
- (void)viewDidLoad
{
[super viewDidLoad];
self.imageCache = [[NSCache alloc] init];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.textLabel.text = [[tableData objectAtIndex:indexPath.row] valueForKey:@"name"];
cell.textLabel.font = [UIFont fontWithName:@"BebasNeue" size:24];
cell.textLabel.textColor = [UIColor whiteColor];
UIImage *cachedImage = [imageCache objectForKey:@"indexObject"];
if (cachedImage) {
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = cachedImage;
});
}
else {
NSString *imageURLString=[[tableData objectAtIndex:indexPath.row] valueForKey:@"picture"];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *url = [NSURL URLWithString:imageURLString];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
UIImage *tmpImage = [[UIImage alloc] initWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
UITableViewCell *newsCell = [self.grillMenuTable cellForRowAtIndexPath:indexPath];
[imageCache setObject:tmpImage forKey:@"indexObject"];
if (newsCell)
{
newsCell.imageView.image=tmpImage;
[newsCell setNeedsLayout];
}
});
});
}
return cell;
}
I used the following code as Joe advise, but still cell.imageview.image always nil.
NSString *imageURLString=[[tableData objectAtIndex:indexPath.row] valueForKey:@"picture"];
[[DLImageLoader sharedInstance] loadImageFromUrl:imageURLString
completed:^(NSError *error, UIImage *imgData) {
cell.imageView.image = imgData;
}];