Ios 如何缓存tableview的图像?

Ios 如何缓存tableview的图像?,ios,caching,Ios,Caching,我有以下代码: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ //P1 UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell Identifier"] autor

我有以下代码:

- (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和photoURLs。我正在尝试将已下载的图像缓存到本地NSDictionary中。问题是没有加载图像。甚至没有加载.png占位符图像。

要将其保存在应用程序的文档目录中:

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中。

我不想将其写入磁盘,因为我不想在下次发布时使用它。每次用户启动应用程序时,他可能希望搜索不同的图像。我只需要将它保存在本地内存中,然后在调用ApplicationIdentinterBackground时清除缓存路径。