Your setup should be:
NSFetchRequest *request=[[NSFetchRequest alloc] initWithEntityName:@"Car"];
NSSortDescriptor *sortDesc=[[NSSortDescriptor alloc] initWithKey:@"category.name" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sortDesc]];
fetchController=[[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:delegate.managedContext
sectionNameKeyPath:@"category.name"
cacheName:nil];
category.name
assume that the reverse relationship for Category
items
is Car
category
(one-to-many relation)
Please note that you might want to change the sort descriptor to sort by some Car
property
Edit:
After you posted your model and current code you cannot section your data by Category
name, as it is a many-to-many relationship.
You cannot have duplicate items for different sections.
If Car
'c' belongs to categories 'g1' and 'g2' you would either need to build the data structure yourself or introduce an intermediary entity that link between car and categories and it will be the one the request will be base upon.
Edit 2:
In your project, you set your carRelation
as to-one to a Categories
entity this will allow you to form the following request:
NSFetchRequest *request=[[NSFetchRequest alloc] initWithEntityName:@"Car"];
NSSortDescriptor *sortDesc=[[NSSortDescriptor alloc] initWithKey:@"carName" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sortDesc]];
fetchController=[[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:delegate.managedContext
sectionNameKeyPath:@"carRelation.categoryName"
cacheName:nil];
This would still not show categories with no cars in them (as it should as you have a cars view and a categories view).
Edit 3:
Your code corrections for CarViewController.m
:
-(void) getData{
AppDelegate *del=(AppDelegate*)[UIApplication sharedApplication].delegate;
NSFetchRequest *req=[[NSFetchRequest alloc] initWithEntityName:@"Car"];
NSSortDescriptor *descriptor1=[[NSSortDescriptor alloc] initWithKey:@"carRelationship.categoryName" ascending:YES];
NSSortDescriptor *descriptor2=[[NSSortDescriptor alloc] initWithKey:@"carName" ascending:YES];
[req setSortDescriptors:@[descriptor1,descriptor2]];
fetchController=[[NSFetchedResultsController alloc] initWithFetchRequest:req managedObjectContext:del.managedContext sectionNameKeyPath:@"carRelationship.categoryName" cacheName:nil];
NSError *fetchError;
fetchController.delegate=self;
[fetchController performFetch:&fetchError];
NSLog(@"Fetch ERROR= %@",fetchError);
}
- (NSString*) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
id<NSFetchedResultsSectionInfo> sectionInfo=[[fetchController sections] objectAtIndex:section];
return [sectionInfo name];
}
As I explained before, This would still not show categories with no cars in them