I have a to-many relationship, e.g. A student has many classes.
Why is it when I run the following code _classes does NOT have the new Cls object in it? Yet when I close the app and reopen it does.
And as a follow up question, How would I get the new list of classes right after adding adding a new one?
NSMutableSet* classes = [student mutableSetValueForKey:@"classes"];
NSManagedObject* cls = [NSEntityDescription insertNewObjectForEntityForName:@"Cls" inManagedObjectContext:context];
[cls setValue:name forKey:@"name"];
[student addClassesObject:cls];
NSError* err;
[context save:&err];
NSMutableSet* _classes = [student mutableSetValueForKey:@"classes"];
And this is what my addClassesObject: operation looks like (auto generated by XCode)
- (void)addClassesObject:(Cls*)cls
{
}
Thank you!
You can’t add objects to the set directly. You need to use Core Data generated accessors or your own custom ones. Look in your .h file and you should see something along the lines of
And
So for your particular case, you would do the following once you have your Cls object:
Then perform you save and you should be able to retrieve the classes set. FYI, calling this method and the relatd NSSet relatd method also sets up the reverse relationship for you.
Good luck
T