1

カスタムセルを使用してUITableViewに画像を読み込むためにこのコードを使用しています

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

static NSString *CellIdentifier = @"CustomCell";

CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
    for (id currentObject in topLevelObjects) {
        if ([currentObject isKindOfClass:[CustomCell class]]) {
            cell = (CustomCell *) currentObject;
            break;
        }
    }

    NSString *tempString = [arrayThumbs objectAtIndex:indexPath.row];
    NSURL *imageURL = [NSURL URLWithString:tempString];
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
    UIImage *image = [UIImage imageWithData:imageData];
    cell.img.image = image;

}

return cell;
}

上記のコードでは、上下にスクロールしても問題はありませんが、画像が正しく表示されず、一部の画像がテーブルで繰り返されます。たとえば、配列が1から10までの10個の画像を保持し、配列が正しい場合などです。順番に、私がテーブルに入れる画像は、1、2、3、4、3、3、1、10、8、9のようなものです。

しかし、私がこのコードを使用するとき

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

static NSString *CellIdentifier = @"CustomCell";

CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
    for (id currentObject in topLevelObjects) {
        if ([currentObject isKindOfClass:[CustomCell class]]) {
            cell = (CustomCell *) currentObject;
            break;
        }
    }

}

NSString *tempString = [arrayThumbs objectAtIndex:indexPath.row];
    NSURL *imageURL = [NSURL URLWithString:tempString];
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
    UIImage *image = [UIImage imageWithData:imageData];
    cell.img.image = image;

return cell;
}

画像は正常に並べられており、重複はありませんが、テーブルの一番下までスクロールしてから一番上までスクロールすると、テーブルが2〜3秒間フリーズします。

これを解決する方法はありますか?

配列には、http://www.website.com/image.jpgなどの画像へのリンクが含まれています

カスタムセルにはIBOutletUIImageView60x60が含まれ、サーバーから読み込まれる画像も60x60です。

4

1 に答える 1

8

次のコードを試して、スレッド内の画像をダウンロードしてください。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSString *tempString = [arrayThumbs objectAtIndex:indexPath.row];
    NSURL *imageURL = [NSURL URLWithString:tempString];
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
    UIImage *image = [UIImage imageWithData:imageData];
    dispatch_async(dispatch_get_main_queue(), ^{
      cell.img.image = image;
    });
});
于 2013-03-17T08:25:18.760 に答える