I have core data entity: “mole,” which I display in a TableView. When I select each in turn, I pass the selected mole to the next NIB using …
controller.mole = [moleArray objectAtIndex:indexPath.row]; // pass the relevant mole to next NIB
When second NIB loads, I want to retrieve just the “details” for just the “mole” selected. I am using the following:
NSManagedObjectContext *context = [mole managedObjectContext]; // find details for the selected mole
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Details" inManagedObjectContext:context];
[request setEntity:entity];
// now sort
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"detailsDate" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
// Having created a fetch request, you now execute it. The events array needs to be mutable, so make a mutable copy of the result.
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[context executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
NSLog(@"details mutableFetchResults = nil");
}
// The final steps are to set the view controller’s events array instance variable and to release objects that were allocated.
[self setDetailsArray:mutableFetchResults];
[mutableFetchResults release];
[request release];
Trouble is the “detailsArray” is returning the Details of all the Moles. I cannot seem to retrieve the Details for just the specific Mole selected. I presume setting “context” is incorrect. Help appreciated.
Does the
Moleentity have a to-many relationship withDetails? If so, you can traverse that relationship and not have to execute a fetch request. Let’s say you do have such a relationship and that it’s calleddetails. You can do this:The trick is that relationships are modeled as
NSSetobjects, so you’ll still need to sort the value to get an ordered array.