CoreData is a framework that helps you manage the model layer objects in your application and it’s quite simple to use as some of the needed code can be automatically generated.
CoreData has been written in Objective-C times (sounds like it has been ages 👀) and there are few issues (or shall I call them „restrictions”) with this framework while using it together with Swift.
In this article I will try to stick to
CoreData staff only as much as possible, you won’t find any information creating the whole application and I assume you know basics about Swift and iOS development. Also… one more important thing — try to not think about
CoreData the same as you think about SQL databases, it is and it works a little bit different.
If you are familiar with the CoreData basics and want to know how to generate model’s classes manually just jump to the end of the article.
I have created a sample project — you can find it on GitHub.
Let’s get started!
While creating new project you can check the mark Use Core Data to include a little bit of boilerplate code in your application — it contains support for saving Core Data and gives us a persistent container which can be used to load store to our application, this will also add an empty data model file to the project. Both those methods are created in the
Once you open Data Model file (
.xcdatamodeld extension) you will see editor where we can add entities, attributes in entities, fetch requests etc. Let’s start with creating an entity — call it
Article. Now we can add some attributes to it — we will make this sample as simple as possible so just create just two attributes and call them
Content. By now we should have model configured as you can see below:
Since article should usually always have a title and some content let’s make those non-optional (although remember Core Data is still an Objective-C framework, so it’s not the same optional to which you are used to in Swift) — you can do it by unchecking the Optional checkbox in the Utilities on the right.
Awesome! As I mentioned at the beginning, with basic configuration all our models will be automatically generated as classes so all we have to do now is just start saving and fetching data from our Core Data model.
We have to populate our model with some data first — create a function in a view controller
I created a reference to
AppDelegate here since we will need that to save our articles in the store.
- The managed object context associated with the main queue. It is an object of
- Since our entity was automatically generated we can easily create its object in the code.
- We fill article with some random title and content (you can find the randomString function in the sample project, it’s just a copy-paste iAhmed’s answer on StackOverflow.
- Simple call to
AppDelegatethat saves our changes in the context.
That was quite simple, wasn’t it 🙂
But… does it actually got saved? Let’s fetch those article(s) and check if they are where they should be — in our store. Fetching is a little bit more complicated… just kidding, it’s a few lines of code longer but will not take longer than few minutes to do some basic fetching. Do not forget to import
CoreData framework if you do that in a file that is not already importing it like
- Create a fetch request. Since the code is automatically generated we can easily call extension’s function that creates a request for us — it returns
- You can configure your request — I won’t get into details too much but among the other things you can create a predicate that will fetch only objects with given precondition.
- Fetches all objects (articles in our case) from the context’s store. Since it’s generic method and takes our request as the parameter, the result will be cast to the proper object.
- Loops through all fetched articles and prints their title.
Removing objects from the store is as easy as above operations. All we have to do is create/fetch object(s) that we want to remove and just call delete on the context, giving an object to remove as the parameter.
- Load articles (
NSManagedObject’s objects) using the previous function.
- Loops through articles and deletes them.
Automatic does not really mean better, so let’s write our models manually so we can take advantage of optional values (who knows, maybe someday it will be generated considering the optional values). Go back to data model’s editor and in the Utilities under Class section, change
Once we do that the project will no longer compile so all we have to do it is create our own
CoreDatais an Objective-C framework we have to make our class available in Objective-C and Objective-C runtime.
- Name the class the same as it is named in the data model editor and inherit from
- Add properties to match attributes from the model — here we can add some nice stuff. I did not do that in my sample project but ie. We can create our own types and aliases and use them here or we can add some extra properties that are not mentioned in the model so temporarily store them.
- Extension with a
fetchRequestmethod to make it compatible with previous implementation and… well… isn’t it just a nice way to create fetch requests?
Writing models on your own has one huge advantage — you can create aliases or wrappers for any attribute to make it easier for others to understand models (If you want me to write more about that just let me know in comments below).
Auto-generated classes and extensions are stored in
DerivedData directory so actually it’s harder to maintain those between a group of people — each time someone changes something in the model, everyone in the team has to re-generate them (ie. by clearing
DerivedData first). There is a similar issue with manual classes — have to keep them in sync with model manually but personally, I like to have everything in the control.