Does anyone have a tutorial or source code that shows a to-many relationship being used, where the user add elements in on the fly? I would just like to have a look because reading about it hasnt been much help.
Does anyone have a tutorial or source code that shows a to-many relationship being
Share
People are often confused by to-many relationships because one entity represents the relationship as a set while the other represents it as a single object. Take the following entities:
In EntityA, the relationship
beesis a set because there maybe many EntityB objects in the relationship. So, using Key-Value coding, you would have to access the relationship using amutableSetForKey:expanding everything out to see the detail would like so:…or more compactly:
If you set from the EntityB side, however, you are only adding a single object so you can just use setValueForKey: directly like so:
That’s if you use generic NSManagedObject instances to represent your entities. If you create custom subclasses then you have properties and methods to do the setting for you:
Remember as well that with managed objects, setting one side of a relationship defined as reciprocal automatically set the other side as well and removing works the same way.
Update
You don’t create relationships with attributes, in this case
namebut rather with an object, in this case an instances of thePersonentity/class. Each individualPersonobject is completely separate from all otherPersonobjects even if they have the same value in theirnameattribute.You must obtain a reference to any particular
Parentobject. If you have just inserted a newParentobject then you already have a reference to it. If it is already been inserted/persisted, then you create a fetch with a predicate that will return the proper object. Once you have the correctParentobject you then just add theTimeobjects to the relationship.So, if your entity looks like this pseudo-code:
… and you are using generic NSManagedObjects to instatiate you entities, you set the relationship between an existing
Parentobject and newTimeobject something like this:Note that if you set the relationship from the
Timeobject’s side, you can use setValue:ForKey: because from theTimeobject’s perspective the relationship is just one object to one object.It is really quite simple once you start thinking in objects instead of databases. Each object you insert in a context is unique even if it shares attributes with other objects of the same entity/class. That is why you can set a relationship between specific objects without necessarily worrying about the values stored in their attributes.