2

我有以下代码:

- (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 中。问题是图像未加载。甚至还没有 loading.png 占位符图像。

4

1 回答 1

3

您想将其保存在应用程序的 Documents 目录中:

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

于 2013-02-18T23:09:52.243 回答