I've got what is hopefully a simple question - I've got two entities - List and ListItem - and there's a one-to-many relationship set up between them, all good.
My problem comes when I'm trying to perform a fetchrequest which will return the listitems sectioned up by an attribute of the listitem. I can't perform a fetchrequest directly on the listItem objects because there's no way to say 'Where List = 'xxxxx'', so I had something like the following:
- (NSFetchedResultsController *)getListItems {
// Init a fetch request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"List" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"listItem.productName" ascending:YES selector:nil];
NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor];
[fetchRequest setSortDescriptors:descriptors];
// Init the fetched results controller
NSError *error;
self.globalFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"listItem.productName" cacheName:@"listItems"];
self.globalFetchedResultsController.delegate = self;
if (![[self globalFetchedResultsController] performFetch:&e开发者_Go百科rror]) NSLog(@"Error: %@", [error localizedDescription]);
[fetchRequest release];
[sortDescriptor release];
return self.globalFetchedResultsController;
}
Now, this errors because it's saying I can't use a one-to-many relationship in the sort descriptor - but it also requires that I have a sort descriptor, so I'm not sure the correct way to be doing this. Any help would be great.
If you want to fetch and section ListItems, then you should be using "ListItem" as your entity for the fetch.
In this case, there is a way to say "fetch all ListItem objects Where List = 'xxxxx'", it's called a predicate (NSPredicate).
Try something like this (where "list" is the name of the ListItem relationship with List):
NSPredicate *pred = [NSPredicate predicateWithFormat:@"list == %@", listObject];
[fetchRequest setPredicate:pred];
Also, see the Predicate Programming Guide.
精彩评论