I have an entity class, correctly defined in a managed context.
This class has a one-to-many relationship with another class.
Xcode 4 graphic facilities correctly created the derived classes, and the relationship is represented by a NSSet.
I am wondering how the creation of the relation classes is managed.
I mean, for creating the main entity I am using the
NSManagedObject *newEntity = [NSEntityDescription
insertNewObjectForEntityForName:@"EntityName"
inManagedObjectContext:context];
But what about the relationship in NSSet ? Do I need to create it in the same way as a parent entity and store it regularly in NSSet ?
NSManagedObject *child = [NSEntityDescription insertNewObjectForEntityForName:@"ChildName" inManagedObjectContext:context];
NSSet *childSet = [..set creation with child..];
newEntity.child = childSet;
// save newEntity in context
If yes, because NSSet is an object why doesn’t it need to be created starting from the context ? Such question could be applied to all the ‘normal’ properties in the entity, an NSString is an object too, why a simple newEntity.prop=@”” is enough ?
For to-many relationships NSManagedObject has a
mutableSetValueForKey:method that returns the set you would use. WithnewEntityandchilddefined as above you’d do something like this:But you said you had Xcode generate custom subclasses for your Core Data entities, so you have a convenience method defined in the
Parentclass which would be named something likeaddChildObject:. Using that you could replace the above with a simpler version, but you’ll also need to declarenewEntityas an instance of this subclass instead of as a generic NSManagedObject: