検索語の結果が取り込まれたテーブルビューがあります。結果の多くには、URL からロードする必要がある画像がありますが、すべてではありません。私はもともと、メインスレッドのメソッドでURLから画像をcellForRowAtIndexPath
取得していましたが、これは完全に機能しましたが、テーブルビューのスクロールが各画像に一時的に「スタック」したため、途切れ途切れになりました。
そこで、バックグラウンド スレッドで画像を読み込んでみることにしました。これが私のcellForRowAtIndexPath
方法です。URL は resultsArray に格納され、インデックスはセルの行に対応します。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[sBar resignFirstResponder];
if (indexPath.row != ([resultsArray count]))
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ResultCell"];
UIImageView * bookImage = (UIImageView *)[cell viewWithTag:102];
//set blank immediately so repeats are not shown
bookImage.image = NULL;
//get a dispatch queue
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//this will start the image loading in bg
dispatch_async(concurrentQueue, ^{
NSData *image = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[[resultsArray objectAtIndex:indexPath.row] thumbnailURL]]];
//this will set the image when loading is finished
dispatch_async(dispatch_get_main_queue(), ^{
bookImage.image = [UIImage imageWithData:image];
if(bookImage.image == nil)
{
bookImage.image = [UIImage imageNamed:@"no_image.jpg"];
}
});
});
return cell;
}
// This is for the last cell, which loads 10 additional items when touched
// Not relevant for this question, I think, but I'll leave it here anyway
else{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"More"];
UILabel *detailLabel = (UILabel *)[cell viewWithTag:101];
detailLabel.text = [NSString stringWithFormat:@"Showing %d of %d results", [resultsArray count], [total intValue]];
if ([UIApplication sharedApplication].networkActivityIndicatorVisible == NO) {
cell.userInteractionEnabled = YES;
}
return cell;
}
}
テーブルビューがゆっくりとスクロールすると、画像はすべて適切なセルに読み込まれます。これは、画像がセルのタイトルと一致するため確認できますが、画像以外のすべての設定を省略して、この質問のために短くしました. ただし、スクロールを速くすると、特に低速のインターネット接続をシミュレートすると、画像が間違ったセルに読み込まれ始めます。セルの再利用と関係があると思います。なぜなら、一番上に向かってすばやくスクロールすると、ビューを離れたばかりのセルの画像が、入ったばかりのセルになってしまうことがよくあるからです。bookImage.image = NULL; だと思いました。行はそれが起こらないことを保証しますが、私はそうではないと思います. バックグラウンド スレッドがよくわからないのですが、最終的に URL から画像が読み込まれると、どのセルを対象としていたか分からなくなったのでしょうか? 何が起こっているのか知っていますか?フィードバックをお寄せいただきありがとうございます。