2013-02-18 87 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