how does CoreData manage class relationship creation?

◇◆丶佛笑我妖孽 提交于 2019-12-12 14:53:44

问题


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 ?


回答1:


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];


来源:https://stackoverflow.com/questions/6437122/how-does-coredata-manage-class-relationship-creation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!