Reputation: 5590
I have a DataModel that has a Category, SubCategory, and DetailedItem entities. Category has a 1-to-many to the SubCategory. Each SubCategory has a 1-to-many relationship to DetailedItem. So a Category has a Set of subCategories and for each SubCategory it has a Set of detailedItems.
Category has a Set property of subCategories, and a Name property. SubCategory has a Set property of detailedItems, a Name Property, and Category parent property
My question is how can I use NSFetchedResultsController to retrieve all the detailedItems from a given SubCategory in a given Category.
I'm trying something like this but I think my NSPredicate is incorrect
if (__fetchedResultsController == nil) {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"DetailedItem" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entityDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Category.name CONTAINS[c] 'Movies'"];
[fetchRequest setPredicate:predicate];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; // probably not needed
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
NSFetchedResultsController *fetchedResults = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[self managedObjectContext] sectionNameKeyPath:nil cacheName:@"AllItems"];
fetchedResults.delegate = self;
__fetchedResultsController = fetchedResults;
NSError *error;
if (![__fetchedResultsController performFetch:&error]) {
NSLog(@"Error fetching");
}
[sortDescriptor release];
[fetchRequest release];
}
The Goal being if Category == Food and SubCategory == Meat, then i'm getting a list of all detailedItems that fall under that Category & SubCategory. If anything isn't clear I'll try to provide more context.
Upvotes: 0
Views: 488
Reputation: 64428
If your datamodel looks like:
Category{
name:string
subCategories<-->>SubCategory.category
}
SubCategory{
name:string
category<<-->Category.subCategories
detailedItems<-->>DetailItem.subCategory
}
DetailedItem{
name:string
subCategory<<-->SubCategory.detailedItems
}
... and you want a table of DetailedItem
objects, you set the fetch entity to DetailedItem
and then you have all your keypaths begin from the DetailItem
entity.
If you just have the names of the Category
and SubCategory
objects then you could connstruct a predicate like:
NSPredicate *p = [NSPredicate predicateWithFormat:@"subCategory.name==%@ AND subCategory.category.name==%@", subCatName,catName];
Note that if you have duplicate name values in either entity's objects, you will get all matching objects.
If you have the actual Category
and SubCategory
objects in hand you can do a faster test with:
NSPredicate *p = [NSPredicate predicateWithFormat:@"subCategory==%@ AND subCategory.category==%@", aSubCatObj,aCatObj];
Upvotes: 1