Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Swift - How to store array with Core Data?

I'm new to iOS development and was wanting to know which data type I should specify to store multiple strings (array). The app is to do with food and I need to store multiple ingredients as one attribute.

I was thinking of making ingredient as entity, but I just want to make it easy for a starter. I have read about transformable type but people don't seem to recommend using it to store arrays.

like image 442
Seong Lee Avatar asked Mar 13 '15 09:03

Seong Lee


People also ask

Can you store an array in Core Data?

There are two steps to storing an array of a custom struct or class in Core Data. The first step is to create a Core Data entity for your custom struct or class. The second step is to add a to-many relationship in the Core Data entity where you want to store the array.

How do I save an array in Swift?

Let's take a look at an example. We access the shared defaults object through the standard class property of the UserDefaults class. We then create an array of strings and store the array in the user's defaults database by invoking the set(_:forKey:) method of the UserDefaults database.


2 Answers

Warning: opinionated answer ahead.

You don't.

Storing things in an array does not make anything easier for you. On the contrary, it will make things much harder just an hour in. Imagine you want to show all Recipes that contain a selected Ingredient. That wouldn't be easy with your array hack, with a proper model it's only a couple line of code.

I would recommend to use a good old relationship with a "Join-entity".

basic Recipe data model

Yes, this is more complicated than hacking something together that barely works. But it's the correct way.

like image 74
Matthias Bauch Avatar answered Oct 27 '22 00:10

Matthias Bauch


What you was thinking of is exactly what you should do. Core Data is made to store values in array like structure. You should create entity Ingredients and connect your Food entity (or whatever you would like to call it) with relationship with Ingredients entity.

like image 27
Wojtek Avatar answered Oct 26 '22 22:10

Wojtek