How to correctly configure CoreData datamodel and NSManagedObjects for a to-many relationship?
I feel i have misconfigured the xcdatamodeld file, but I can’t find what’s wrong.
I generated a new single view project with CoreData selected. The following code is a simple as I can explain the problem.
Parent *parent = [NSEntityDescription insertNewObjectForEntityForName:@"Parent" inManagedObjectContext:[self managedObjectContext]];
Child *child = [NSEntityDescription insertNewObjectForEntityForName:@"Child" inManagedObjectContext:[self managedObjectContext]];
child.parent = parent;
When i call
[parent.children count];
Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[Child count]: unrecognized selector sent to instance 0x7450370’
When I call
NSMutableSet *children = [parent mutableSetValueForKey:@"children"];
‘NSManagedObjects of entity ‘Parent’ do not support -mutableSetValueForKey: for the property ‘children”
Also, there doesn’t seem to be any generated add/remove methods being generated to modify the children collection such as
- (void)addChildObject:(Child *)value;
- (void)removeChildObject:(Child *)value;
xcdatamodeld
Entities
-
Child
relationship: parent
destination: Parent
inverse: children -
Parent
relationship: children
destination: Child
inverse: parent -
Configurations (Default)
entity: Child
class: Childentity: Parent
class: Parent
Parent.h
@interface Parent : NSManagedObject
@property (nonatomic, retain) NSSet *children;
@end
Parent.m
@implementation Parent
@dynamic children;
@end
Child.h
@interface Child : NSManagedObject
@property (nonatomic, retain) NSManagedObject *parent;
@end
Child.m
@implementation Child
@dynamic parent;
@end
You should use “Editor -> Create NSManagedObject Subclass…” in Xcode to create the managed object subclass files. This ensures that you have the correct accessor functions. Another advantage is that Xcode then knows the accessor functions and does autocompletion.
Make also sure that the
childrenrelationship is defined as “To-Many Relationship” in the Core Data Inspector.