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からフェッチし、jsonはflickrから結果を取得して、photoNamesとphotoURLsにデータを入力します。ダウンロード済みの画像をローカルのNSDictionaryにキャッシュしようとしています。問題は、画像がロードされていないことです。Loading.pngプレースホルダー画像すらありません。

4

1 に答える 1

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内に辞書を保存することをお勧めします。

于 2013-02-18T23:09:52.243 に答える