UICollectionView reloadItemsAtIndexPaths

Jdizzle Foshizzle picture Jdizzle Foshizzle · Jan 13, 2014 · Viewed 14k times · Source

I've been trying to wrap my head around the reloadItemsAtIndexPaths method of UICollectionView.

I have an array of objects called objectsArray. When a user scrolls to the bottom of my collection view, I fetch the next batch of objects from the backend and append it to objectsArray by calling [objectsArray addObjectsFromArray:objects]; After doing so, I call [self.collectionView reloadData] which I know is expensive.

I'd like to optimize with the code below but I get an assertion failure when calling reloadItemsAtIndexPaths.

    if (self.searchPage == 0) {
        parseObjectsArray = [[NSMutableArray alloc] initWithArray:relevantDeals];
        [self.collectionView reloadData];

    } else {

        NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
        for (int i = 0; i < [relevantDeals count]; i++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
            [indexPaths addObject:indexPath];
        }

        [parseObjectsArray addObjectsFromArray:relevantDeals];
        [self.collectionView reloadItemsAtIndexPaths:indexPaths];
        //[self.collectionView reloadData];
    }

Error: * Assertion failure in -[UICollectionView _endItemAnimations], /SourceCache/UIKit/UIKit-2903.2/UICollectionView.m:3716

Any help/tips is greatly appreciated.

Thanks!

Answer

Dan Treiman picture Dan Treiman · Jan 13, 2014

It looks like the items being added are new, in other words you are adding items which weren't there before. In that case, just replace reloadItemsAtIndexPaths:indexPaths with insertItemsAtIndexPaths:

[self.collectionView insertItemsAtIndexPaths:indexPaths]; // Use this for newly added rows
//[self.collectionView reloadItemsAtIndexPaths:indexPaths]; // Use this for existing rows which have changed