Question

I have a collection view that displays instances of CatViewController views:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CatCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCatCellId forIndexPath:indexPath];

    [cell updateCat:[self.dataSource catAtIndex:indexPath.row]]; //catAtIndex will return a Cat Core Data object

    return cell;
}

CatCell looks like this:

- (void)prepareForReuse {
    [super prepareForReuse];
    [self.catVC.view removeFromSuperview];
    self.catVC = nil;
}

- (void)updateCat:(Cat*)cat {
    self.catVC = [[CatViewController alloc] initWithNibName:nil bundle:nil];
    self.catVC.view.frame = self.bounds;
    [self.contentView addSubview:self.catVC.view];
    self.catVC.cat = cat;
}

self.catVC.cat is what causes the CatViewController to configure itself with all the view data associated with a Cat object. The problem is that when the UICollectionView scrolls, it pauses briefly as the new CatViewController is created and displayed. Obviously I want the collection view to be completely smooth, and have the view for each cell appear when it's ready, without blocking the main thread.

This is easy and well-documented to do with images, but I'm struggling to do the same with a view controller's view.

Was it helpful?

Solution

Reuse as much of your controller and view infrastructure as possible. There is a reason that table and collection views offer cell reuse - tear down and recreation is expensive.

Collection view memory management is the art of reuse. By not reusing the controller and it's view you are subverting the cell reuse (because you destroy and recreate 90% of the cell content each time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top