2

画像を含むエントリで TableView を表示するアプリを書いています。cellForRowAtIndexPathメソッド内で次のコード行を実行して、画像を取得しようとしています。

cell.detailTextLabel.text =  [artistData objectForKey:generesKey];
dispatch_async(backgroundQueue, ^{
         NSURL *url_img = [NSURL URLWithString:[artistData objectForKey:pictureKey]];
        NSData* data = [NSData dataWithContentsOfURL:
                         url_img];
        cell.imageView.image = [UIImage imageWithData:data];
        [self performSelectorOnMainThread:@selector(refreshCell:) withObject:cell waitUntilDone:YES];
    });

画像を設定した後、次を含むセレクターを実行します。

-(void)refreshCell:(UITableViewCell*)cell{
    [cell setNeedsDisplay];
    [self.view setNeedsDisplay];
    [self.tableViewOutlet setNeedsDisplay];
}

画像は表示されませんが、セルをクリックするか、リスト全体をスクロールすると、画像が表示されます。ビューが更新されないのはなぜですか? 私は何かを逃しましたか?

4

3 に答える 3

2

を呼び出すことで、いつでもセルをリロードできます[self.tableView reloadRowsAtIndexPaths@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

画像のダウンロードに成功したら無限ループを防ぐために、結果をキャッシュする必要があります。キャッシュする期間はあなた次第です。

 NSCache *imageCache = [[NSCache alloc] init];
 imageCache.name = @"My Image Cache";
 UIImage *image = [imageCache objectForKey:url_img];
 if (image) {
    cell.imageView.image = image;
 } else {
    // Do your dispatch async to fetch the image.

    // Once you get the image do
    [imageCache setObject:[UIImage imageWithData:data] forKey:url_img];
}

imageCache を ViewController レベルのプロパティにする必要があります。毎回作成しないでくださいcellForRowAtIndexPath

于 2014-12-09T18:13:39.380 に答える