1
votes

I see following example of adding to-many relationship back to CoreData

where 'currentDog' have many 'walks'

walk.date = NSDate()
let walks = currentDog.walks!.mutableCopy() as! NSMutableOrderedSet
walks.addObject(walk)
currentDog.walks = walks.copy() as? NSOrderedSet

and this is the way they insert the new walk

I was wondering why is it done that way? when one can simply do

walk.date = NSData()
walk.dog = currentDog

A more general question. Why would there be a need to insert an object to a Set before saving? When you can simply set the relationship of an object to it's related object or parent.

1

1 Answers

-1
votes

If the relationship is ordered then you may want to insert into the set. If not, and assuming your relationship is bi-directional as all should be, then your second example of setting the to-one end of the relationship is preferred because it's less code and therefore easier to maintain and read.