Saving And Fetching Data In CoreData


A device always has to be connected to a server to send the request and get responses back to the server but no device can always be connected to the internet. Some applications show messages like there is no internet connection and some allow the user to do basic operations in the application, as in Whatsapp, where we can see chats and send messages to a friend and when we connect with the internet it's delivered to friend's device. Whatsapp stores all messages in storage and when the internet comes back it sends messages to the server, this is called local data storage. Some applications like ToDo list, Task, and Memo applications do not need to connect with the server all the time, internet connection is required for this application only to backup or sync the Todo, Tasks & Memo, etc. They can use offline data storage.

Some Ways to store data in iOS applications

  1. User Defaults
  2. Property List
  3. CoreData
  4. SQLite
  5. KeyChain

What is CoreData? 

 Apple developer's documentation says it is not a database it is a framework introduced by APPLE in MacOS X 10.4 Tiger and iOS with iPhone SDK 3.0, it is used to store large amounts of data locally in the iOS applications. It is not a database but it uses SQLite to store data, we can do operations like save, fetch, update and delete data in SQLite using CoreData.

Let's start with CoreData

Open Xcode create new iOS project single view application name the application and hit use core data and click next.

After clicking next we have a new file named CoreDataDemo.xcedatamodeld, In this file we will create our entity. Entity in CoreData is similar to entity in Database, basically, an entity in CoreData is an instance for class NSEntityDescription which contain all information about that entity as attributes like an entity Employee has attributes EmployeeName, EmployeeId, EmployeeSkill, etc.

Now we will add entity by clicking AddEntity button at the bottom and name it college. Every entity has some attributes as college also has attributes like name, city, address, and university. Here we will add college attributes by clicking plus button. Here we are adding four attributes, we also have to give the type of attributes as String type to all attributes.

We have created an entity college now we will create the NSManagedObject subclass, Click on Editor on the navigation bar and go to create the NSManagedObjectsubclass.

Now we have two files,


In this file we have a College class whose type is NSManagesdObject, it is a generic class that implements all the basic behavior required by the CoreData model object.

import Foundation
import CoreData
public class College: NSManagedObject {


in this file, we have all the properties that we have created for the college entity and a function fetch request() whose return type is NSFetchRequest which is required to fetch data from core data.

import Foundation
import CoreData
extension College {
    @nonobjc public class func fetchRequest() -> NSFetchRequest<College> {
        return NSFetchRequest<College>(entityName: "College")
    @NSManaged public var name: String?
    @NSManaged public var city: String?
    @NSManaged public var address: String?
    @NSManaged public var university: String?

When we write code we have to take care of readability, that's why we will create a swift file DatabaseHelper which will contain save and fetch function that we will use when we will have to save or fetch data from CoreData.

Saving data into CoreData

func save(object: [String: String]) {
    let context = (UIApplication.shared.delegate as!AppDelegate).persistentContainer.viewContext
    let college = NSEntityDescription.insertNewObject(forEntityName: "College", into: context) as!College = object["name"] = object["city"]
    college.address = object["address"] = object["university"]
    do {
        print("successfully saved")
    } catch {
        print("Could not save")

In save function we are passing a dictionary that contains name, city, address, and university that we want to save into CoreData. When we added CoreData to our project then a stack of CoreData methods already created in AppDelegate File. There is a persistent container that will be responsible for all the operations that we will perform into CoreData like save, fetch, delete and update. There is another function created in AppDelegate SaveContext which is used to save our data into CoreData.

Now we will create context of that persistent container that contains ViewContext method where we will save our data, here we create a variable college that stores the description of entity College and we will insert new object into context that will save our data, then we perform method that will create exception so we use try catch method to handle that exception. We have successfully saved our college data into CoreData.

Fetching Data From CoreData

func fetch() - > [College] {
    var collegeData = [College]()
    do {
        collegeData =
            try context.fetch(College.fetchRequest())
    } catch {
        print("couldnt fetch")
    return collegeData

We saved our data into CoreData now we have to fetch all the data stored in CoreData, for this we have already written method in College+CoreDataProperties.swift file fetchRequest. We have created a function fetch() whose return type is array of College(Entity). For fetching the data we just write context.fetch and pass fetchRequest that will generate an exception so we handle it by writing try catch, so we fetched our all the data from CoreData.

Key points about CoreData

  • CoreData is an important method to store our data locally. We can fetch our saved data even after terminating the app, according to apple developer's documentation it reduced 50-70 % of your code.
  • Managed Object model contains entity, attributes and relations
  • Entity in CoreData is an instance of NSEntityDescription which contains information like attributes.
  • Attributes are all information attached with an entity.
  • NSManagedObjectContext is reponsible to save() and fetch() data from CoreData

Thanks for reading this article.