8

I've got two entities, one named exercise and the other named workout. I would like to store several different exercises in each workout object.

What is the correct logic here? Create an array of exercises in each workout?

Douwe Maan
  • 6,888
  • 2
  • 34
  • 35
Abdulla
  • 1,117
  • 4
  • 21
  • 44

2 Answers2

24

You can't create arrays in Core Data. You can simulate them, however, using To-Many Relationships. Add a relationship to your Workout entity called, say, exercises. Then set its Destination to the Exercise entity and check the "To-Many Relationship" checkbox. Note that the exercises will be stored as an NSSet, not an NSArray, so they will not be ordered. If you want them to be in a specific order, I would recommend using the BWOrderedManagedObject subclass.

Max B.
  • 881
  • 10
  • 21
Steve Harrison
  • 121,227
  • 16
  • 87
  • 72
  • 14
    Since iOS 5, it is possible to sort the relationship. Just tick the checkbox "ordered" on the relationship in the editor. – Bjinse Oct 16 '12 at 10:11
  • 1
    Thanks for this great, 10 yr old explanation, @SteveHarrison! – Fattie Feb 07 '20 at 15:43
7

As the (still perfect) decade old answer of @SteveHarrison explains, you just click for "relationship", but do select "to-many"

enter image description here

so, some entity has many "Reply" items. (I put "CD" in front of all entity names, hence, "CDReply".)

After you next rebuild, for free, you get

enter image description here

hence, say you have one of your CDPost which is p

The code is this simple

for oneJsonReply in yourJson {
    r = CDReply.your code to convert ( oneJsonReply ) to a CDReply
    p.addToReplys( r )
Fattie
  • 27,874
  • 70
  • 431
  • 719