Core Data 如何为关系设置值?
Core Data How to set a value for relationship?
假设,我在 parent 和 child 之间有 One-to-Many 关系。
如何通过代码设置child的parent?类似于:
[child setValue: ParentManagedObject forKey: ParentRelationship];
其中 child - 在 child managedObject 中与 parent.
有关系
ParentManagedObject - 是 parent 的 object,在应用程序启动时提取到单例
ParentRelationship - 是 .xcdatamodeld
中的一个键
我知道我可以为 parent 和 child 创建 NSManagedObjectSubclass 并像
那样做
child.ParentRelationship = ParentManagedObject;
但我想知道如何在不创建子类的情况下进行操作。
当然你可以使用KVC获取或设置NSManagedObject
的属性。
对于一对一或一对多关系,您可以使用:
[child setValue:parent forKey:parentKey];
对于多对一或多对多使用:
NSMutableSet *relationshipSet = [parent mutableSetValueForKey:childrenKey];
[relationshipSet addObject:child];
其中 parent
和 child
是 NSManagedObject
个实例。
假设,我在 parent 和 child 之间有 One-to-Many 关系。
如何通过代码设置child的parent?类似于:
[child setValue: ParentManagedObject forKey: ParentRelationship];
其中 child - 在 child managedObject 中与 parent.
有关系
ParentManagedObject - 是 parent 的 object,在应用程序启动时提取到单例
ParentRelationship - 是 .xcdatamodeld
我知道我可以为 parent 和 child 创建 NSManagedObjectSubclass 并像
那样做child.ParentRelationship = ParentManagedObject;
但我想知道如何在不创建子类的情况下进行操作。
当然你可以使用KVC获取或设置NSManagedObject
的属性。
对于一对一或一对多关系,您可以使用:
[child setValue:parent forKey:parentKey];
对于多对一或多对多使用:
NSMutableSet *relationshipSet = [parent mutableSetValueForKey:childrenKey];
[relationshipSet addObject:child];
其中 parent
和 child
是 NSManagedObject
个实例。