CoreData 如何管理类关系创建?
我有一个实体类,在托管上下文中正确定义。 该类与另一个类具有一对多的关系。
Xcode 4 图形工具正确创建了派生类,并且关系由 NSSet 表示。
我想知道如何管理关系类的创建。 我的意思是,为了创建主要实体,我使用的是
NSManagedObject *newEntity = [NSEntityDescription
insertNewObjectForEntityForName:@"EntityName"
inManagedObjectContext:context];
但是 NSSet 中的关系怎么样?我是否需要以与父实体相同的方式创建它并定期将其存储在 NSSet 中?
NSManagedObject *child = [NSEntityDescription insertNewObjectForEntityForName:@"ChildName" inManagedObjectContext:context];
NSSet *childSet = [..set creation with child..];
newEntity.child = childSet;
// save newEntity in context
如果是,因为 NSSet 是一个对象,为什么不需要从上下文开始创建它?这样的问题可以应用于实体中的所有“正常”属性,NSString 也是一个对象,为什么一个简单的 newEntity.prop=@"" 就足够了?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于多对多关系,NSManagedObject 有一个
mutableSetValueForKey:
方法,该方法返回您将使用的集合。使用上面定义的newEntity
和child
你会做这样的事情:但是你说你让 Xcode 为你的 Core Data 实体生成自定义子类,所以你有一个方便的方法在
Parent
类中定义,其名称类似于addChildObject:
。使用它,您可以用更简单的版本替换上面的内容,但您还需要将newEntity
声明为该子类的实例,而不是通用的 NSManagedObject:For to-many relationships NSManagedObject has a
mutableSetValueForKey:
method that returns the set you would use. WithnewEntity
andchild
defined 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
Parent
class which would be named something likeaddChildObject:
. Using that you could replace the above with a simpler version, but you'll also need to declarenewEntity
as an instance of this subclass instead of as a generic NSManagedObject: