In UITableViewCell, UIImageView content repeats after some cells using AFNetworking

540 views Asked by At

The content is distinct on all the cells on the first page but as we scroll down, only the UIImageView is repeated though the UILabels are distinct.

I am using [UIImageView setImageWithURL:(NSURL *)url] from AFNetworking which was included in the RestKit. Heres the implementation

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RClubTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"RClubTableViewCell"];
    RClubObject * club = _clubs[indexPath.row];
    [cell.clubImageView setImageWithURL:[NSURL URLWithString:club.clubImageURL]];
    cell.nameLabel.text = club.clubName;
    return cell;
}

Seems like iOS is somehow using the previously created cells. Would like to have completely fresh cells while scrolling.

3

There are 3 answers

8
Wain On

You need to call setImageWithURL:placeholderImage: with a non-nil placeholder image to have the old image removed from the image view.

1
Ganesh Somani On

I guess you missed reallocation in your cellForRowAtIndexPath: Your code should be something like this

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RClubTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"RClubTableViewCell"];
    if(cell == nil)
    {
       cell = [[RClubTableViewCell alloc] init];
    }
    RClubObject * club = _clubs[indexPath.row];
    [cell.clubImageView setImageWithURL:[NSURL URLWithString:club.clubImageURL]];
    cell.nameLabel.text = club.clubName;
    return cell;
}

Update :

Okay. I just had the same issue. Here what my search over google tells me : Since you are downloading the image in async and also scrolling, it gets downloaded and attached to other cells which are currently visible

Solution:

  1. add tag to each imageView using indexpath.row
  2. Use function setImageWithURL: placeholderImage:success:
  3. In success block reload the cell using the tag value.

Though I haven't tested this I feel this should work. PS : Let me know if this works I also would have to do the same then :)

0
Eric Hedstrom On

Yes, iOS is reusing the previously created cells. That is what this line of code does, so that the app does not have to spend the time creating a new cell from scratch:

RClubTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"RClubTableViewCell"];

Clear the image from the recycled cell before adding the new image for this cell:

cell.clubImageView.image = nil;
[cell.clubImageView setImageWithURL:[NSURL URLWithString:club.clubImageURL]];
cell.nameLabel.text = club.clubName;
return cell;

Alternatively, you could create a new cell from scratch instead of dequeuing one.