Core Data learning note

Sellen Wei
3 min readAug 10, 2018

I have another video which is only 25 minutes (click here: https://www.youtube.com/watch?v=klZfcT087L4) explain how to use core data in iOS development to save user’s input data. I am not gonna explain what is core data and why use it. The purpose of writing this story is just a learning note or quick tutorial I could use in future work to quickly set up environment and start using core data.

  1. generate new project, choose core data:
choose use core data

2. add new file under the folder, new file type should be core data- data modal, you could have several data modal, as much as you need, just make sure you seperate them

3. add entity name (managed class)from “add entity” and add property for each classes (make sure you check the box if property is optional) if you property is a managed class, choose “transformable” as dataType

4. make sure set up the settings in this way:

5. and generate swift for this managed class, check the property you want to generate.

6. Then you need to have another swift file to generate the persistentContainer and the function saveContext() to save when necessary, seperate the persistentContainer with other containers if you have multiple managed Object. make sure the name “RecipeModel” matches you core data file’s name.

7. add entity into core data persistentContainer

8. get object from core data persistentContainer

context.delete(recipesArray[index]) //use delete method to delete one of the element in the array.

Summery: if you have an array of managed object need to be saved, better to use core data, but if you only need to save one or two object, maybe userDefault is a good enough solution because you do not need to go through all of the code here. Remember: both core data and userDefault require to have NSCoding related functions if you choose to save an complicate class. So the preparation work for both of them are similar.

more code:

core data class: https://www.raywenderlich.com/3444-beginning-core-data

--

--