简体   繁体   中英

Store Array as String to Core Data in Swift

I have a question about core data. My entity look like this:

  • Game (GameID, GameName, Players, timestamp)
  • User (UserID, Email, status...)
  • Message (GameID, MessageText, SendersID)

In the table Game I want to store all players who are in this game. The problem is that they can be 2 or more so I have to store an array... I thought about two solutions..

My first solution would be storing a string into members which would look like this:

3,4,5,6,11

And then split it into an array

let members = fetchedData.Players.characters.split{$0 == ","}.map(String.init)

The second one: (I think this is the "cleaner" version)

I'll make my entity look like this:

Game (GameID, GameName, timestamp)

and add another entity:

Players (GameID, UserID)

What do you think? What advantages do I have if I make another Entity? (I think I'll have better performance but I also think that I'll have to much data)

If you are going to store an array of simple data, like ints, then using a transformable attribute is reasonable (see answer from Bartlomiej Semanczyk). Note, however, that from core data's perspective, the attribute is just a bag of bytes, with no meaning, and no searching. Also, changing one entry of the array changes the entire attribute.

Using another entity would be best advised for anything else. Don't worry about the extra storage overhead. Depending on how many players you have, you may or may not have better performance, but that's not the point.

It is cleaner, gives you more options, and fits better with the core data model.

Specifically, with the entity, you can now easily know things like "which games is player X playing?" "how many players playing all games?" "list all players", etc.

Now, when you establish the relationship, there is no need to add the "gameid" to the player entity.

Also, when you establish the relationship, you probably want to make many-to-many seeing as a game can have many players, and a player can be involved in many games.

  1. Why do not you read How to save Array to CoreData?

  2. However you can convert array to String using:

     let arrayAsString = [1, 2, 3].description //[1, 2, 3] 

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