0

Hi found the answer here: Images getting mixed up in a UITableView - XML parsing

I'm parsing an XML file with links to images which I'm putting into a UITable. For some reason the pictures are getting completely mixed up when I scroll down in the table. Here's the code I'm using for my UITable:

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

    static NSString *CellIdentifier = @"Cell";
    Tweet *currentTweet = [[xmlParser tweets] objectAtIndex:indexPath.row];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

        CGRect imageFrame = CGRectMake(2, 8, 40, 40);
        customImage = [[UIImageView alloc] initWithFrame:imageFrame];
        [cell.contentView addSubview:customImage];

    }

    NSString *picURL = [currentTweet pic];
    if (![picURL hasPrefix:@"http:"]) {
        picURL = [@"http:" stringByAppendingString:picURL];
    }

    customImage.image = [UIImage imageWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:picURL]]];

    return cell;
}

Any idea what I'm doing wrong? Any help is seriously appreciated. Thx!

Community
  • 1
  • 1

2 Answers2

1

Its because you are dequeueing reusable cells. It is recycling a cell that had a previously used image in it.

I noticed that you are setting the image in the same if block that you are initializing the cell. If I were you I'd move [cell.contentView addSubview:customImage]; to right before your return statement. This way when it recycles a dequeued cell, it won't have an image in it.

Kyle Redfearn
  • 2,172
  • 16
  • 34
0

Are the images being downloaded from the web?

If so then the delay in downloading the images will be causing this. You'll need to do it in a multi threaded way.

Take a look at this example...

Question about Apple's LazyTableImages sample - Doesn't behave exactly like the app store

There are also many tutorials online about lazy loading with images and UITableViews.

Community
  • 1
  • 1
Fogmeister
  • 76,236
  • 42
  • 207
  • 306