Search code examples
iosswiftcore-datarelationshipnsmanagedobject

Manipulate Relationships in Core Data


I have a NSManagedObject subclass defined like this:

extension Item {
  @NSManaged var name: String
  @NSManaged var parent: Item
  @NSManaged var children: [Item]
}

In order to set the 'parent' attribute, I use this:

anItem.parent = aParent

And I know it will automatically append anItem to aParent.children too.

However, I would like the child item to be added at a specific position. This idea is to have a sorted array of children.

I know I could simply do this:

aParent.childen.insert(anItem, atIndex: specificPosition)

But is there any method to override or operator to overload in order to automatically achieve that ?


Solution

  • Inserting the child at a particular position will not ensure the same sort order later when you fetch. You will need an additional attribute to define the sort order during the fetch.

    Have a look at this answer