My Core Data app has two entities: "Note" and "Marker". The Note entity has a 1-to-many relationship to markers (ie. A note contains many markers). I have a fetchedRequestController which is responsible for fetching all the "Note" entities. After creating 1 note and 1 marker (which belongs to that note) I get an error because the fetchedRequestController fetches both the Marker and Note. The Note is expected but the Marker should not be fetched.
Here is my fetched request controller
TCModel *model = [TCModel sharedModel];
NSManagedObjectContext *context = [model managedObjectContext];
NSParameterAssert(context);
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Note" inManagedObjectContext:context];
NSParameterAssert(entity);
[fetchRequest setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"creationDate" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController *controller = [[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:context
sectionNameKeyPath:nil
cacheName:@"Root"];
NSParameterAssert(controller);
self.fetchedResultsController = controller;
controller.delegate = self;
NSError *error;
BOOL success = [controller performFetch:&error];
if ( success == NO )
{
NSLog(@"Failed to fetch!");
NSParameterAssert(nil);
}
The objects are created using two helper methods and then saved using a third
- (TCNote *)newNote
{
TCNote *note = [NSEntityDescription insertNewObjectForEntityForName:@"Note"
inManagedObjectContext:self.managedObjectContext];
note.creationDate = [NSDate new];
return note;
}
- (TCMarker *)newMarker
{
TCMarker *marker = [NSEntityDescription insertNewObjectForEntityForName:@"Marker"
inManagedObjectContext:self.managedObjectContext];
return marker;
}
- (void)_save
{
NSError *error;
NSLog(@"Saving");
if (![self.managedObjectContext save:&error])
{
NSLog(@"Error saving context: Error = %@", error);
}
}
Here is the console output:
2013-01-03 17:41:12.062 timecode[10269:c07] CoreData: sql: SELECT Z_VERSION, Z_UUID, Z_PLIST FROM Z_METADATA
2013-01-03 17:41:12.063 timecode[10269:c07] CoreData: sql: SELECT t0.Z_ENT, t0.Z_PK, t0.Z_OPT, t0.ZNOTEDATE, t0.ZSCENEDESCRIPTION, t0.ZSCENETITLE, t0.ZTIMECODEDATE, t0.ZDATE, t0.ZTITLE, t0.ZPARENT, t0.Z1_PARENT FROM ZNOTE t0
2013-01-03 17:41:12.064 timecode[10269:c07] CoreData: annotation: sql connection fetch time: 0.0005s
2013-01-03 17:41:12.064 timecode[10269:c07] CoreData: annotation: total fetch execution time: 0.0011s for 2 rows.