FetchedResultsController with sections
ios, nsfetchedresultscontroller
Solution
When you create your NSFetchResultsController use the entity name for the books table in the fetch request.
Then use this...
NSFetchedResultsController *aController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"typePropertyName" cacheName:nil];
typePropertyName will be the path to get from a book to the name of the section it will be in.
It could just be @"typeName" if you have it directly in the Book table or it could be @"type.name" if you have a relationship to a table called `type` and then that table has a field called `name`.
Anyway, that will create a NSFetchedResultsController with the sections in...
Full code will be something like ...
#pragma mark - fetched results controller
- (NSFetchedResultsController*)fetchedResultsController
{
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Book"];
[request setFetchBatchSize:20];
NSSortDescriptor *sdType = [[NSSortDescriptor alloc] initWithKey:@"type.name" ascending:YES];
NSSortDescriptor *sdName = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
[request setSortDescriptors:@[sdType, sdName]];
NSFetchedResultsController *aController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"type.name" cacheName:nil];
aController.delegate = self;
self.fetchedResultsController = aController;
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _fetchedResultsController;
}
Then in the tableViewController you can have this...
- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
id <NSFetchedResultsSectionInfo> sectionInfo = [self.fetchedResultsController sections][section];
return [sectionInfo name]
}
This will then use the section name as the header for each section.
Problem
I am writing a small app in which I uses coredata, I have data like subjects which contains Maths, Science, and other Books. Other books can be added or deleted, but maths and science cannot be deleted,they will get added by default when new student is added. When I fetch my results, i should get all the book names including maths and science. What I want do is display the data in three section with headers as Maths, Science, and Others. Maths and science will contain only one row, i.e, maths or science. And all other books should be in reading section. How to proceed to achieve this?