Why can't I save NSSet to 'to-many' relationship in coredata?
In one of my core data entities I have a one to many relationship with another entity. Say my family Entity has a to-many relationship with person.
I can create families and persons no problem. but 开发者_开发技巧when I do a:
self.myFamily.people = [NSSet setWithArray:myPersonArray];
There doesn't seem to be a set assigned to the relationship 'people'. I'm currently re-factoring some code away from the viewcontrollers into a singleton. Could this possible have anything to do with it? I can save all other object, I can create and delete managed objects I just can't assign a set of objects to a relationship!
There are a couple of reasons why this might not work. First, if you are trying to do this in the object's initializer, it won't properly set the value. When the initializer is called, the object has not yet been added to the context, so setting a value may not have any effect. Secondly, Apple advises against setting a to-many relationship directly (sorry, I can't find the documentation for this statement, but it said something like if you do it too much it might stop working). Instead, you should modify the mutable set it creates automatically, either using the dynamically created accessors or by using the value returned from mutableSetValueForKey:
.
[self.myFamily addPeople:[NSSet setWithArray:myPersonArray]];
or
[[self.myFamily mutableSetValueForKey:@"people"] addObjectsFromArray:myPersonArray];
or, since you want to change the whole set
[[self.myFamily mutableSetValueForKey:@"people"] setSet:[NSSet setWithArray:myPersonArray]];
You should use mutableSetValueForKey:
instead of the set object returned by the accessor because the object returned by the accessor won't call KVC notifications, but the object from mutableSetValueForKey:
will.
The most likely cause of this error as you report it is trying to add a set of the wrong class of objects. You can only add objects of the entity/class that is defined for the relationship in the data model.
So, if you have a data model like this:
Family{
name:string
people<-->>Person.family
}
Person{
name:string
family<<-->Family.people
}
... and you have NSManagedObject subclasses of FamilyMO
and PersonMO
, then you can only assign a set of PersonMO
objects to the Family.people
relationship. If you tried to assign a set like this:
NSSet *badSet=[NSSet setWithObjects:PersonMO1, PersonMO2, FamilyMO1, PersonMO2,nil];
aFamilyMO.people=badSet;
... it would fail and IIRC, it would do so silently.
精彩评论