1

検索語の結果が取り込まれたテーブルビューがあります。結果の多くには、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 から画像が読み込まれると、どのセルを対象としていたか分からなくなったのでしょうか? 何が起こっているのか知っていますか?フィードバックをお寄せいただきありがとうございます。

4

3 に答える 3

1

推測では:

  1. セル Aがロードされ、非同期リクエスト Aが開始されます。
  2. 要求が完了する前に、テーブルがスクロールされ、セル Aが画面外にスクロールします。
  3. セル Aはリサイクルされ、セル Bとしてデキューされます。
  4. セル Bが非同期要求B を開始します。
  5. 非同期リクエスト Aが完了し、セル A (現在はセル B ) のイメージ ビューが更新されます。

これを修正するには、非同期リクエストへのハンドルを保持し、セルがデキューされたときにキャンセルする必要があります。

于 2012-03-28T16:28:09.017 に答える
1

私のアプローチ (AFNetworking ライブラリに依存しています)。次の zip ファイルのクラスをプロジェクトに含めます。

http://dl.dropbox.com/u/6487838/imageloading.zip

独自のカスタム セルを作成します。コードは次のようになります (メソッド-setComment:-willMoveToSuperview:メソッドを確認してください)。

#import "CommentCell.h"
#import "CommentCellView.h"
#import "MBImageLoader.h"


@interface CommentCell ()
@property (nonatomic, strong) UIImageView     *imageView;
@property (nonatomic, strong) CommentCellView *cellView;
@property (nonatomic, assign) CellStyle       style;
@end


@implementation CommentCell

@synthesize cellView, style = _style, imageView, comment = _comment, showCounter;

- (id)initWithStyle:(CellStyle)style reuseIdentifier:(NSString *)reuseIdentifier;
{
    self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    if (self)
    {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.opaque = YES;
        self.style = style;
        self.showCounter = YES;


        CGFloat width = 53.0f;
        CGFloat x = (style == CellStyleRight) ? 320.0f - 10.0f - width : 10.0f;
        CGRect frame = CGRectMake(x, 10.0f, width, 53.0f);
        self.imageView = [[UIImageView alloc] initWithFrame:frame];
        imageView.image = [UIImage imageNamed:@"User.png"];
        [self.contentView addSubview:imageView];


        self.cellView = [[CommentCellView alloc] initWithFrame:self.frame cell:self];
        cellView.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:cellView];
    }
    return self;
}

- (void)dealloc
{
    self.comment = nil;
    self.cellView = nil;
    self.imageView = nil;
}

- (void)willMoveToSuperview:(UIView *)newSuperview
{
    [super willMoveToSuperview:newSuperview];

    if (!newSuperview)
    {
        [[MBImageLoader sharedLoader] cancelLoadImageAtURL:_comment.iconURL forTarget:self];
    }
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)setFrame:(CGRect)newFrame 
{
    [super setFrame:newFrame];

    CGRect bounds = self.bounds;
    bounds.size.height -= 1; 
    cellView.frame = bounds;
}

- (void)setNeedsDisplay 
{
    [super setNeedsDisplay];

    [cellView setNeedsDisplay];
}

- (void)setComment:(MBComment *)comment
{
    if (_comment == comment) 
        return;

    _comment = comment;

    if (comment.icon == nil)
    {
        imageView.image = nil;

        [[MBImageLoader sharedLoader] loadImageForTarget:self withURL:comment.iconURL success:^ (UIImage *image) 
         {
             comment.icon = image;

             imageView.alpha = 0.0f;
             imageView.image = image;

             [UIView animateWithDuration:0.5f delay:0.0f options:UIViewAnimationOptionAllowUserInteraction animations:^ {
                 imageView.alpha = 1.0f;                 
             } completion:^ (BOOL finished) {}];             

         } failure:^ (NSError *error) 
         {
             DLog(@"%@", error);
         }];
    }
    else 
    {
        imageView.image = comment.icon;
    }

    [self setNeedsDisplay];
}

@end
于 2012-03-29T18:15:39.693 に答える
0


どうやってこれをしたか。

cellForRowAtIndexPath:方法:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath     *)indexPath {

static NSString *cellIdentifier = @"CellIdentificator";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
}
[cell.imageView setImage:nil];

NSData *const cachedImageData = [self.cache objectAtIndex:indexPath.row];
if ([cachedImageData isKindOfClass:[NSData class]]) {
    [cell.imageView setImage:[UIImage imageWithData:cachedImageData]];
} else {
    [self downloadAndCacheImageForIndexPath:indexPath];
}

return cell;

}

downloadAndCacheImageForIndexPath:方法:

- (void)downloadAndCacheImageForIndexPath:(NSIndexPath *)indexPath {

dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(concurrentQueue, ^{
    NSString *const imageStringURL = [NSString stringWithFormat:@"%@%.2d.png", IMG_URL, indexPath.row];

    NSData *image = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageStringURL]];
    [self.cache replaceObjectAtIndex:indexPath.row withObject:image];

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:indexPath.row inSection:0]]withRowAnimation:UITableViewRowAnimationNone];
    });
    [image release];
});

}

self.cacheロードされた画像を保存するためにNSMutableArray使用するものです。画像の量の s がプリロードされていますNSDataself.cache[NSNull null]

BR。
ユージーン。

于 2012-03-29T18:06:24.903 に答える