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