4
votes

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!

3

3 Answers

5
votes

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
4
votes

The assertion error was misleading. It wasn't until after I implemented

            @try
            {
                [self.collectionView insertItemsAtIndexPaths:indexPaths];
            }
            @catch (NSException *except)
            {
                NSLog(@"DEBUG: failure to insertItemsAtIndexPaths.  %@", except.description);
            }

Did I realize was calculating my indexPaths wrong. My index offset for the new objects was off by one making my collectionview think I was adding more objects than I specified in numberOfItemsInSection.

Thanks for all those who attempted to help!

0
votes

This error often arises when you increase/decrease the number of items in the array but it doesn't match the data source method

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

Are you updating it appropriately?