Core Data in iOS & macOS: A Complete Guide to CRUD, Predicates, and Data Management

Core Data in iOS & macOS: A Complete Guide to CRUD, Predicates, and Data Management
Back to blog

Core Data is a graphical and persistence framework, which is used in Apple devices with operating systems macOS and iOS. Core Data was first introduced in Mac OS X 10.4 Tiger and iOS with iPhone SDK 3.0. It allows data to be organized in a relational entity–attribute model manner, so that it can be serialized into XML, binary, or SQLite stores. 

You can utilize Core Data to save your application’s permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device. 

Core Data automatically reflects your schema to a CloudKit container to sync data across multiple devices in a single iCloud account. 

You can specify your data’s types and relationships and develop respective class definitions. Core Data can manage object instances at runtime through Core Data’s Data Model editor. 

Core Data has certain disadvantages, as it can only store data once entered, which is not like a typical SQL database.  

In other words, Core Data keeps an object graph in memory; hence, it can only work with records in memory. You can understand this like, suppose you want to delete or update 100 records, so first you need to load all the records in memory. 

Earlier, Core Data had some issues with multithreading, but over the years, the improvements in the development of Core Data have made it compatible with multithreading. 

Undo and Redo of Individual or Batched Changes

CoreData has this feature of undo and redo. The undo manager tracks down the changes that occur in the data and can roll them back whenever it is needed. This makes the work of the developer way easier.  

View Synchronization 

CoreData provides table view and collection view, which are helpful when you want to synchronize your views and data. 

Versioning and Migration 

CoreData helps you with versioning your data model and migration of user data with the evolution of the app. 

Background Data Tasks 

CoreData performs UI-Blocking data tasks, like parsing JSON into objects, but in the background, which can further be cached or stored to reduce server roundtrips. 

CRUD in Swift (Create, Read, Update, Delete)

Let’s create a new project to understand how Core Data works, and let’s select “Use Core Data”. You can also add Core Data to your project afterward, but this is easier, as everything will be served to you.

Once the project is created, you will see a file like CoreDataTest.xcdatamodeld already created, you can also add the file to an existing project.

Once you click it, you will see a tool. This tool allows you to configure entities, which represent data models. 

Here you can define some of the things for each and every entity, but remember that Attributes and Relationships will be most important. 

Core Data Stack

Inside the AppDelegate, the Core Data Stack code has clear documentation in the form of comments; it sets up the persistent container and saves the data, and if there are any changes, then they are saved. 

You can easily save and fetch the context from Core Data Stack because the AppDelegate is the first file that executes as soon as the app is launched. 

Since you have turned our data into the User entity, you can now add some records and save them to the Core Data.

Saving Records in Core Data

The procedure of adding the records to Core Data includes the following tasks: 

  • Refer to the persistent container 

  • Create the context 

  • Create an entity 

  • Create a new record 

  • For each key, you need to set values for the records. 

Since the container is set up in the AppDelegates. Hence, you need to refer to that container. 

let appDelegate = UIApplication.shared.delegate as! AppDelegate

Let’s create a context from this container.

let context = appDelegate.persistentContainer.viewContext

Let’s create an entity and new user records.

let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
let newUser = NSManagedObject(entity: entity!, insertInto: context)

Finally, add some data to your newly created record.

newUser.setValue("Abhishek", forKey: "username")
newUser.setValue("2311", forKey: "password")
newUser.setValue("21", forKey: "age")

Although the methods which are used to save the context already exist in the AppDelegate.swift, but explicit definition of the code can also be done to save the context in the database. Remember to wrap this with do try and catch block, since it will help in exception handling.

do { 
  try context.save()      
 } catch {      
  print("Error saving")
}

Now, each time you run our app, new entities will be added to the records in Core Data. 

Retrieve / Fetching from Core Data

The procedure of fetching the saved data is very straightforward. It has the following task: 

  • Craft and organize the request of type NSFetchRequest for the entity. 

  • Use a predicate for filtering data (if required). 

  • Fetch the result from the context in the form of an array of [NSManagedObject]. 

  • Now you need to iterate through an array to obtain a value for the specific key.

let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
        //request.predicate = NSPredicate(format: "age = %@", "21")
request.returnsObjectsAsFaults = false        
do {
            let result = try context.fetch(request)
            for data in result as! [NSManagedObject] 
{
    print(data.value(forKey: "username") as! String)
  }

       } catch {

           print("Failed")
}

Update Data in Core Data

To update the records, first of all, you need to fetch data with a use of predicate as shown above in the Retrieving data process. Then, below few steps to follow: 

  • Frame the request with a predicate for the entity  

  • Fetch the record, post that, set the New value with the key 

  • And the Last Save context similar to the Create Data. 

For all these tasks, you can use the same code above. 

Delete Data in Core Data

In order to delete the record, first of all, you need to find the object that you want to delete by FetchRequest, then follow the steps below to delete the record: 

  • Formulate the request with a predicate for the entity  

  • Fetch the record that you want to delete 

  • And create context.delete(object) call (ref image attached below) 

let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
let context = self.appDel.managedObjectContext!
context.del(data)
do {
try context.save()
}
catch {
    // Handle Error
}

Core Data: NSPredicate In Swift

Predicates are simple tests that are used to filter out the data that you need in our resultant array of data. The test will be applied to every object in your Core Data entity. Just like simple SQL commands, predicates are used.

let query = "Suraj"

let request: NSFetchRequest&lt;Person&gt; = Person.fetchRequest()request.predicate = NSPredicate(format: "name LIKE %@", query)request.predicate = NSPredicate(format: "name == %@", query)

Just like “LIKE” in the above example, NSPredicate has many keywords such as:

CONTAINS, MATCHES, BEGINS WITH, and ENDS WITH.

Conclusion

Core Data is a great fit for applications that require managing a complex object graph. Core Data can only do its charm because it maintains the object graph it works in memory. There are many complicated things that we can do with core data, like – adding Predicates and complex relationships of databases, tracking data changes, and more. As you utilize more Core Data and dive in, things get more complicated, but these are the fundamentals of Core Data. 

Frequently Asked Questions

Q: What is Core Data used for in iOS development?

You can store and organize data with the help of Core Data framework on a device. It allows you to save data locally and keep your data synced across devices.

Q: Is Core Data the same as a database?

No. Core Data is a data management framework to manage data effectively. It uses XML or SQLite to store data.

Q: How do you perform CRUD operations in Core Data?

CRUD stands for Create, Read, Update, and Delete, helping you:

  1. Add new records

  2. Fetch existing records

  3. Update saved information

  4. Delete records you no longer need

Q: Can Core Data work with large datasets?

Yes. Core Data helps maintain app performance even with thousands of records by loading data only when needed.

Q: What does CRUD stand for?

CRUD simply stands to Create, Read, Update, and Delete, these are the four basic actions for working with datasets.

Mobile App Development Services

Do you want to leverage mobile technology for your business? Cynoteck is a one-stop Mobile app Development Services provider. We provide iOS and Android application development services so that you can reach your target audience on any device.

Get A Consultation

Real-World Results

Discover How We Deliver Results

blog-postPost preview
Pooja Sharma 01 Jan 1970

TypeScript Vs JavaScript Vs ECMAScript – Know The Difference

In this article, you will know the major differences between Typescript, Javascript, and Ecmascript.

blog-postPost preview
Subodh Dharmwan 01 Jan 1970

Core Data in iOS & macOS: A Complete Guide to CRUD, Predicates, and Data Management

Core Data is one of Apple's most popular frameworks for iOS and macOS apps. Core data is used to manage the model layer objects in applications.

blog-postPost preview
Pooja Sharma 01 Jan 1970

Top 9 Software Development Models to Choose From: Phases and Applications

Here are the top 9 Software Development Models to Choose From: Phases and Applications.

blog-postPost preview
Pooja Sharma 06 Jul 2025

Software Development Time Estimation: A Practice Guide

This hands-on software development time estimation guide describes the basics of estimating time, provides practical time-estimating techniques.

blog-postPost preview
Pooja Sharma 14 Aug 2025

A Quick Guide to Install Laravel 8 on Windows 10 XAMPP

Laravel 8 is a PHP-based web application framework, here is a quick guide on how to install Laravel 8 on windows 10 xampp.

Turning expertise into action for your business.

We are more than just developers and consultants—we are your partners in navigating the digital landscape. Let us be the engine behind your next big success while you focus on your core vision.

Explore Opportunities!