Travis Tubbs
Travis Tubbs

Reputation: 877

Why does this load improperly the first time but correctly upon refresh?

So in my last question, I was wondering how to make it a circle, but now I am trying to resize the circle as well. For some reason, The circle does not show up as a circle (it shows up as the square that it is). until I pull it down to refresh it and it gets most of them correctly then.

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

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

    PFObject *group = groups[indexPath.row];
     //if(group[PF_GROUP_LOGO] != nil){
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ // go to a background thread to load the image and not interfere with the UI
       UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:group[PF_GROUP_LOGO]]]];
        dispatch_async(dispatch_get_main_queue(), ^{ // synchronize back to the main thread to update the UI with your loaded image

            cell.imageView.image = image;
            cell.imageView.image = ResizeImage(image, 60, 60, 1);
            cell.imageView.layer.cornerRadius = cell.imageView.frame.size.height /2;
            cell.imageView.layer.masksToBounds = YES;
            cell.imageView.layer.borderWidth = 0;
            cell.textLabel.text = group[PF_GROUP_NAME];
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%d users", (int) [group[PF_GROUP_MEMBERS] count]];
            cell.detailTextLabel.textColor = [UIColor lightGrayColor];

        });
    });
    return cell;

}

Upvotes: 0

Views: 50

Answers (1)

davbryn
davbryn

Reputation: 7176

cellForRowAtIndexPath is called on the main thread whenever the tableview needs to recycle a cell for display.

You start loading the image on a background thread and update the recycled cell once that completes on the main thread

Thing is, you can't guarantee that the cell hasn't been recycled by that point - especially if the tableview is scrolled before the cell is updated on the main thread (or even if setNeedsDisplay will be triggered on the cell).

If you wan't to style the cell before the image loads, you should do it in prepareForReuse with a custom UITableViewCell subclass - this way, the cell is ready before it is displayed.

Upvotes: 1

Related Questions