How to design "ordering" of objects with Core Data

122 views Asked by At

I have a Bullet object and a List object. A List has many bullets and a Bullet can belong to many Lists.

But I need to guarantee ordering of Bullet objects. For example, a List object should always have #1 Bullet A #2 Bullet B and #3 Bullet C in that order. Another List (List B) might have those same bullets, but in a different order, #1 Bullet B, #2 Bullet C and #3 Bullet A.

NSSet doesn't store ordering, and Core Data doesn't allow arrays.

What should I do? Can I do something with properties here?

Edits: After listening to the comments below, I realized that it's a "Many to Many" relationship between lists and bullets ... For example, a Bullet (name: "Egg") can appear in the List (name: "Dairy") and the List (name: "Food").

3

There are 3 answers

0
Oleksii Taran On BEST ANSWER

Use ordered relationship. It is mapped to NSOrderedSet.

1
iris On

I would insert a third entity, let's say BulletsInList, with an attribute, where you can store your ordering Position (1, 2, 3 etc).

Instead of the relationship between List and Bullet you can now build a relationship between Bullet and BulletsInList (one Bullet can be contained in many BulletsInList, one BulletsInList belongs to exactly one Bullet) and another between List and BulletsInList (one List may have many BulletsInLists, one BulletsInList belongs to exactly one List).

In short, the BullettsInList Object contains then: 1 List-Object, 1 Bullet-Object and 1 Number-Attribute for your Position.

0
diegomen On

Using ordered relationship it's an option, but iCloud doesn't allow it, so if you plan to use core data on iCloud don't use them, or it will be a pain in the future (based on my own experience).

The solution I recommend it's to extend the List NSManagedObject, let's call it List+Additions, and in that extension, you can have methods which will return the NSSet ordered as you want.