简体   繁体   中英

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 ?

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

A couple misconceptions here:

  1. CoreData to-many relationships are not of type Array , they are Set or NSSet . This can be verified by having your subclass generated by Xcode.
  2. It is possible to to have an ordered relationship - just take a look at the relationship inspector in your Core Data Model. This will change it to a NSOrderedSet
  3. MAJOR CAVEAT to (2) - The order is determined exclusively by the order that you add them - see this link for more info.
  4. It is much more memory intensive to store these as ordered, if you can, have an attribute you can use to order them after fetching.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM