CellForItemAtIndexPath called out of bounds

I have a UICollectionView that uses its own UICollectionViewCell class. The main idea - a collection view will move catalogs and display photos contained in the catalog (results via API calls). The initial view controller displays the UICollectionView , and the UICollectionView on the cells generate a new view with the new UICollectionView . The contents of the directory are stored in NSMutableDictionary with the directory key being the key.

The problem arises when a new view / collectionview is created with a rather short list of photos - usually less than 30. When I rotate the device, the collection view tries to re-display, and the application crashes with "index X outside [0 .. Y]", and X is number greater than Y (last element of the array).

I noticed that this only happens when the newly displayed collection view has fewer elements than the root collection view.

Here are examples of relevant (some of them, anyway) code:

 - (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section { return [[photos objectForKey:api.directoryID] count]; } - (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView { return 1; } - (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath { PhotoCell *photoCell = [cv dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath]; photoCell.photo = [[photos objectForKey:api.directoryID] objectAtIndex:indexPath.row]; return photoCell; } 

At least I would like to try try / catch on cellForItemAtIndexPath , but I don't know where I would put try / catch. Perhaps in a custom UICollectionView ?

Thanks!

+4
source share
1 answer

The problem is here:

 - (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section { return [[photos objectForKey:api.directoryID] count]; } 

I assume that for all your instances of UICollectionView , one delegate and dataSource are used . If so, rewrite the code this way:

 - (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section { if ( view == _firstCollectionView ) { return [[photos objectForKey:api.directoryID] count]; } else if ( view == _secondCollectionView ) { return ...; } } 

You must also rewrite the collectionView:cellForItemAtIndexPath: method this way.

+3
source

All Articles