Core Data Relationships fetch
Ok, I thought I had this but I am not getting the results that I am expecting. Hopefully someone can help.
I have two entities Person and Timesheet with one attribute to-many relationship: Person.timesheet<--->>Timesheet.user. The code below works but when I try to add a second timesheet entry it seems to override the first?
I have looked at the Apple Docs and they are a little vague on this subject.
//Add
NSManagedObjectContext *context = self.managedObjectContext;
Person *personAdded = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context];
Timesheet *timesheet = [NSEntityDescription insertNewObjectForEntityForName:@"Timesheet" inManagedObjectContext:context];;
timesheet.time = @"10:00 Friday";
timesheet.timestamp = [NSDate date];
NSSet *timesheetSet = [NSSet setWithObject:timesheet];
personAdded.name = @"Darren";
personAdded.job = @"Job to be Done";
personAdded.timesheet = timesheetSet;
NSError *error = nil;
[context save:&error];
if (error) {
NSLog(@"[ERROR] COREDATA: Save raised an error - '%@'", [error description]);
}
NSLog(@"[SUCCESS] COREDATA: Inserted new User to database!");
// Load
NSEntityDescription *personEntity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity: personEntity];
error = nil;
NSArray *results = [context 开发者_StackOverflow社区executeFetchRequest:request error:&error];
if (!results || error) {
NSLog(@"[ERROR] COREDATA: Fetch request raised an error - '%@'", [error description]);
[request release];
}
NSLog(@"Results: %@",results);
Person *firstUser = [results objectAtIndex:0];
NSLog(@"First User's name: %@",firstUser.name);
NSLog(@"First User's time %@",[[firstUser.timesheet anyObject] valueForKeyPath:@"timestamp"]);
I am wondering if it could be because I am actually setting the Person.timesheet key with the NSSet and not the actual Table? OR could it be that I am not calling the results correctly?
Thanks, Darren
You should have a generated "CoreDataGeneratedAccessors" method in your Person.h file which gives you a method
[personAdded addTimesheet:timesheetSet];
which creates the links for you ?
Core Data normally generates an add and a remove method for any relationships you define.
Post your person.h file if this is not clear.
精彩评论