I have an entity with attribute "group", cause I want to group into 2 sections the list of my entities by "group" (either 0 or 1)
@property (nonatomic, retain) NSNumber * group;
In my fetchedResultsController, I specify sectionNameKeyPath as "group"
self.fetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest:request managedObjectContext:self.managedObjectContext
sectionNameKeyPath:@"group" cacheName:nil];
How can I return the number of rows in each section inside the method below? I am getting error below:
Terminating app due to uncaught exception 'NSRangeException', reason:
'-[__NSArrayM objectAtIndex:]: index 1 beyond bounds for empty array'
Here is the code:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[[self.fetchedResultsController sections] objectAtIndex:section]
numberOfObjects];
}
Also I tried this, got the same error:
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections]
objectAtIndex:section];
return [sectionInfo numberOfObjects];
Note that I implemented this method as well:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
Did you implement numberOfSectionsInTableView:
? If you don't implement it, the tableView assumes you have 1 section, which would lead to this exception if the fetchedResultsController does not have any sections (i.e. it has no objects).
You must return [sections count]
in numberOfSectionsInTableView:
.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [self.fetchedResultsController.sections count];
}
If you always want to show two sections you have to check if the fetchedResultsController has the requested section. If the fetchedResultsController does not have this section, don't ask it for the number of objects in this action.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSInteger count = 0;
NSInteger realNumberOfSections = [self.fetchedResultsController.sections count];
if (section < realNumberOfSections) {
// fetchedResultsController has this section
id <NSFetchedResultsSectionInfo> sectionInfo = [self.fetchedResultsController.sections objectAtIndex:section];
count = [sectionInfo numberOfObjects];
}
else {
// section not present in fetchedResultsController
count = 0; // for empty section, or 1 if you want to show a "no objects" cell.
}
return count;
}
if you return something other than 0 in the else you have to change tableView:cellForRowAtIndexPath:
as well. Similar to this method you have to check if the fetchedResultsController has an object at the requested indexPath.