Search code examples
core-dataentity-relationship

how does CoreData manage class relationship creation?


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 ?


Solution

  • For to-many relationships NSManagedObject has a mutableSetValueForKey: method that returns the set you would use. With newEntity and child defined as above you'd do something like this:

    NSMutableSet *childObjects = [newEntity mutableSetValueForKey:@"childRelationship"];
    [childObjects addObject:child];
    

    But you said you had Xcode generate custom subclasses for your Core Data entities, so you have a convenience method defined in the Parent class which would be named something like addChildObject:. Using that you could replace the above with a simpler version, but you'll also need to declare newEntity as an instance of this subclass instead of as a generic NSManagedObject:

    Parent *parent = [NSEntityDescription insertNewObjectForEntityForName:@"EntityName" inManagedObjectContext:context];
    NSManagedObject *child = [NSEntityDescription insertNewObjectForEntityForName:@"ChildName" inManagedObjectContext:context];
    
    [parent addChildObject:child];