Core Data in iOS

John Cui
Go Ahead Tours — Tech Blog
3 min readDec 14, 2016

Core Data is an object graph and persistence framework provided by Apple in the OS X and iOS operating systems. It is a very unique feature which stores and maps all kinds of data (text, images, etc) locally with different hierarchies.

Why use Core Data

Core Data is useful when you need to store data which you don’t want to retrieve from a server every time you open your app or when your app needs to be used offline and you still want to keep track of the data.

Advantages

Core Data manages data locally, which means it has a persistent store. Every time the app launches or closes, the data can be loaded or saved instantly at any time.

Core Data has managed to provide many useful features which can save a lot of time. One thing is the graphical object model editor called Core Data Model Editor. It provides an interface for you to create all kinds of entities and attributes in a clear way which shows their relationships. Also, using this model makes it easier to change entities or attributes later on comparing to changing them in the code.

Entities and Attributes

Core Data provides relationship connection function in which you only need to add a relationship in XCModel to show what relationship each entity has with another entity and you can also specify any one-to-one, one-to-many or many-to-many relationships into a single nice clean object-oriented interface. Somehow this just gives an easy way to manage core data like some databases do.

Relationship

Example

We made extensive use of the Core Data framework in the Go Ahead Tours mobile app.

For example, our mobile team decided to use Core Data to save messages in the chat function. So, obviously we need to create a message entity with different attributes like messageIDs and contents like text, images or locations infos.

Also, we need the relation to connect messages with tour since each tour contains an unique chat room and some users may have multiple tours. So we set this as a one-to-many relation in which every message belongs to its unique tour.

So then every time we store the message into the Core Data, we only need to add the specific tour into the message entity. Every message related in the tour will thus have the same key value which relates to the tour. Meanwhile we create a set of messages in the tour class which stores the messages. And every time when we need to retrieve the messages we just need to get the tour and let it return all of the messages.

--

--