marciokoko
marciokoko

Reputation: 4986

How to cache images for a tableview?

I have the following code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//P1
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell Identifier"] autorelease];
cell.textLabel.text = [photoNames objectAtIndex:indexPath.row];

//Check if object for key exists, load from cache, otherwise, load

    id cachedObject = [_cache objectForKey:[photoURLs objectAtIndex:indexPath.row]];

    if (cachedObject == nil) {
        //IF OBJECT IS NIL, SET IT TO PLACEHOLDERS
        cell.imageView.image = cachedObject;
        [self setImage:[UIImage imageNamed:@"loading.png"] forKey:[photoURLs objectAtIndex:indexPath.row]];
        [cell setNeedsLayout];

    } else {
        //fetch imageData
        dispatch_async(kfetchQueue, ^{
            //P1
            NSData *imageData = [NSData dataWithContentsOfURL:[photoURLs objectAtIndex:indexPath.row]];
                dispatch_async(dispatch_get_main_queue(), ^{
                    cell.imageView.image = [UIImage imageWithData:imageData];
                    [self setImage:cell.imageView.image forKey:cell.textLabel.text];
                    [cell setNeedsLayout];
                });
        });
    }
return cell;

}

Other than this, the viewDidLoad method fetches from the web, the json result from flickr, to populate a photoNames and photoURLs. Im trying to cache already downloaded images into a local NSDictionary. The problem is that the images arent loaded. Not even the loading.png placeholder image.

Upvotes: 2

Views: 1128

Answers (1)

Tommy Devoy
Tommy Devoy

Reputation: 13549

You want to save it in the app's Documents directory:

NSData *imageData = UIImagePNGRepresentation(newImage);

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",@"cached"]];

NSLog((@"pre writing to file"));
if (![imageData writeToFile:imagePath atomically:NO]) 
{
    NSLog((@"Failed to cache image data to disk"));
}
else
{
    NSLog((@"the cachedImagedPath is %@",imagePath)); 
}

Then just save the path in your NSMutableDictionary with:

[yourMutableDictionary setObject:theIMagePath forKey:@"CachedImagePath"];

Then retrieve it with something like:

 NSString *theImagePath = [yourMutableDictionary objectForKey:@"cachedImagePath"];
 UIImage *customImage = [UIImage imageWithContentsOfFile:theImagePath];

I recommend saving the dictionary inside NSUserDefaults.

Upvotes: 3

Related Questions