如何缓存tableview的图像?

时间:2013-02-18 23:04:10

标签: ios caching

我有以下代码:

- (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;

}

除此之外,viewDidLoad方法从web获取flickr的json结果,以填充photoNames和photoURL。我试图将已下载的图像缓存到本地NSDictionary中。问题是图像没有加载。甚至不是loading.png占位符图片。

1 个答案:

答案 0 :(得分:3)

您想将其保存在应用程序的Documents目录中:

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)); 
}

然后只需使用以下命令保存NSMutableDictionary中的路径:

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

然后用以下内容检索它:

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

我建议在NSUserDefaults中保存字典。