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占位符图片。
我不希望把它写到磁盘上,因为我不想在下次启动时使用它。每次用户启动应用程序时,他都可能希望搜索不同的图像。我只需要将它保存在本地内存中。 – marciokoko 2013-02-18 23:14:46
然后,只需在调用applicationDidEnterBackground时清除缓存的路径即可。 – 2013-02-19 00:12:00