1

I'm currently looking into CoreData and need to save multiple values per key. In my case I just need to save a couple of strings, max 9, for a single Key in CoreData.

Specifically, I want to save players for a game. My game object already contains relationship objects to these players, but I also want to save the Player names as records on the game object itself, as players can be deleted by my users and I want my game objects to be immune for that.

I know in Cloudkit you can set the value of a certain key to e.g. "set of strings", and this can be done in CoreData relationships to when creating a one-to-many relationship. I was wondering if there is a by-the-book way to do this in regular CoreData key-value pairs as well.

Joris416
  • 4,751
  • 5
  • 32
  • 59

2 Answers2

2

It's easier to think about CoreData as objects rather than low-level data storage. It's not really designed as a key/value system (except in the sense that any object's properties can be thought of as a dictionary).

For the example you give, it might be more in keeping with CoreData's object persistence style to flag deleted players as unavailable rather than removing them, so that your history remains intact.

Phillip Mills
  • 30,888
  • 4
  • 42
  • 57
  • Thank you very much for you quick reply. As I understand from your answer, you suggest a workaround for my specific situaton, which helps me in this case. I can solve my problem the way you suggest but, looking at the core of the question: Do you know whether and how it is possible to save multiple values per key in a coredata Object property? – Joris416 Feb 16 '16 at 14:32
  • Not directly. Again, thinking about "keys" is something of a mismatch for how it works. If it's a simple list, you could fake it with a concatenated string. For more complex situations, see the answer here: http://stackoverflow.com/questions/1562676/best-practice-array-dictionary-as-a-core-data-entity-attribute – Phillip Mills Feb 16 '16 at 14:43
  • Okay wait, This does work so far. But say my users wants to reset his/her statistics by deleting his/her player object, and then create another player object with the exact same name. If I do this now, In the new object I can see all statistics from the deleted player object as well. Any solution for this? – Joris416 Feb 17 '16 at 14:40
  • How would you see both sets of statistics if they are different objects? (They **are** different objects, right?) The name is only one property. – Phillip Mills Feb 17 '16 at 15:27
2

You could use an attribute of type Transformable to store your set. NSArray and NSSet conform to NSCoding so CoreData can take care of all data transforming, archiving and unarchiving for you.

Robin Dorpe
  • 344
  • 3
  • 7