You said in a comment that fetchedObjects
returns 8 objects. In numberOfSectionsInCollectionView
you use this to calculate the number of sections in the collection view:
NSInteger photoCount = [[self.fetchedResultsController fetchedObjects] count];
NSInteger sectionCount = (photoCount + 3) / 3;
return sectionCount;
Assuming that the count is really 8, that means sectionCount
is 3 (11 / 3
, integer division). Note that you are not asking the fetched results controller how many sections it has, but you are telling the collection view that it should have three sections.
Since you return 3 above, collectionView:numberOfItemsInSection:
will be called 3 times with section values of 0, 1, and 2. You pass the section
value to the fetched results controller:
id <NSFetchedResultsSectionInfo> sectionInfo = [self.fetchedResultsController sections][section];
This only works if the fetched results controller actually has 3 sections. But you never asked it how many sections it has, so there's no guarantee that it has that many sections. In this situation a crash is extremely likely.
What it looks like happened is:
- You didn't use
sectionNameKeyPath
when you created the fetched results controller - Therefore
[self.fetchedResultsController sections]
returns an empty array - But you try to look up an object in that empty array, because you assumed there would be 3 sections without checking whether that is true.
Therefore you crash. You can't just tell the fetched results controller how many sections it should have. The number of sections is based on the fetch results, and there aren't any sections unless you include a sectionNameKeyPath
.