darksky darksky - 4 months ago 87
Objective-C Question

UICollectionView Performing Updates using performBatchUpdates

I have a

which I am trying to insert items into it dynamically/with animation. So I have some function that downloads images asynchronously and would like to insert the items in batches.

Once I have my data, I would like to do the following:

[self.collectionView performBatchUpdates:^{
for (UIImage *image in images) {
[self.collectionView insertItemsAtIndexPaths:****]
} completion:nil];

Now in place of the
, I should be passing an array of
, which should point to the location of the new items to be inserted. I am very confused since after providing the location, how do I provide the actual image that should be displayed at that position?

Thank you


contains the size of the data source array,
, before new data is added from the data at

[self.collectionView performBatchUpdates:^{

int resultsSize = [self.results count];
[self.results addObjectsFromArray:newImages];
NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];

for (int i = resultsSize; i < resultsSize + newImages.count; i++)
[arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];

[self.collectionView insertItemsAtIndexPaths:arrayWithIndexPaths];

} completion:nil];


See Inserting, Deleting, and Moving Sections and Items from the "Collection View Programming Guide for iOS":

To insert, delete, or move a single section or item, you must follow these steps:

  1. Update the data in your data source object.
  2. Call the appropriate method of the collection view to insert or delete the section or item.

It is critical that you update your data source before notifying the collection view of any changes. The collection view methods assume that your data source contains the currently correct data. If it does not, the collection view might receive the wrong set of items from your data source or ask for items that are not there and crash your app.

So in your case, you must add an image to the collection view data source first and then call insertItemsAtIndexPaths. The collection view will then ask the data source delegate function to provide the view for the inserted item.