2013-02-18 86 views
2

我有以下代码:如何缓存tableview的图像?

- (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方法从网上,从Flickr JSON结果,取来填充photoNames和photoURLs。我试图缓存已经下载的图像到本地NSDictionary。问题是图像没有加载。甚至不包含loading.png占位符图片。

回答

3

您希望将其保存在应用程序的文件目录:

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

+0

我不希望把它写到磁盘上,因为我不想在下次启动时使用它。每次用户启动应用程序时,他都可能希望搜索不同的图像。我只需要将它保存在本地内存中。 – marciokoko 2013-02-18 23:14:46

+0

然后,只需在调用applicationDidEnterBackground时清除缓存的路径即可。 – 2013-02-19 00:12:00