How to start Core Data(CRUD) in Swift for Beginners

Core Data with Swift

Core Data is a framework provided by Apple that allows developers to manage the storage and retrieval of data in their iOS applications.

It provides a convenient way to work with databases, enabling you to create, read, update, and delete data objects.

Core Data Example (Create, Retrieve, Update and Delete)

let’s begin by creating a single view iOS app with the Core Data module enabled.

ios core data

To start, create a new project and make sure to select the “Use Core Data” option. This will automatically set up the necessary framework and configurations for Core Data integration.

While it’s possible to add the Core Data framework to an existing project, it’s simpler to enable it during the project creation process since it sets up the initial setup for you.

Once the project is created, you’ll notice a file named CoreDataTest.xcdatamodeld is added, which is where you’ll define your data model.

Upon clicking on the CoreDataTest.xcdatamodeld file, you will be presented with a tool that enables you to configure entities, which represent your data models.

Within this tool, you can define various aspects for each entity, with a particular emphasis on Attributes and Relationships for our purposes.

These sections allow you to specify the characteristics of your data entities and establish connections between them.

core data swift
core data swift
core data swift

Now that we have successfully created a project with Core Data support, we can easily observe two notable changes in this Xcode template. These changes include:

  • The new file CoreDataCRUD.xcdatamodeld
  • The AppDelegate.swift file with Core Data Stack code
core data swift

The AppDelegate.swift file contains well-documented comments that explain the Core Data Stack code. In summary, it sets up the persistentContainer and handles saving the data whenever there are any changes. Since the AppDelegate is the first file executed when the app is launched, we can save and fetch the context from the Core Data Stack.

Now that we have defined our data model in the User entity, it’s time to add some records and save them into the CoreData database.

Import with import CoreData in the viewcontroller.swift class.

Create New Records to Core Data

To add the records to Core Data has following tasks

  • Refer to persistentContainer from appdelegate
  • Create the context from persistentContainer
  • Create an entity with User
  • Create new record with this User Entity
  • Set values for the records for each key
func createData(){
        
        //As we know that container is set up in the AppDelegates so we need to refer that container.
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
        
        //We need to create a context from this container
        let managedContext = appDelegate.persistentContainer.viewContext
        
        //Now let’s create an entity and new user records.
        let userEntity = NSEntityDescription.entity(forEntityName: "User", in: managedContext)!
        
        //final, we need to add some data to our newly created record for each keys using
        //here adding 5 data with loop
        
        for i in 1...5 {
            
            let user = NSManagedObject(entity: userEntity, insertInto: managedContext)
            user.setValue("Ankur\(i)", forKeyPath: "username")
            user.setValue("ankur\(i)@test.com", forKey: "email")
            user.setValue("ankur\(i)", forKey: "password")
        }

        //Now we have set all the values. The next step is to save them inside the Core Data
        
        do {
            try managedContext.save()
           
        } catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
        }
    }

Get Retrieve Data

Fetching the saved data is a straightforward process, and it involves the following tasks:

  • Prepare the request of type NSFetchRequest for the entity (User in our example)
  • if required use predicate for filter data
  • Fetch the result from context in the form of array of [NSManagedObject]
  • Iterate through an array to get value for the specific key

Fetch the data from our Users entity using following code :

func retrieveData() {
        
        //As we know that container is set up in the AppDelegates so we need to refer that container.
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
        
        //We need to create a context from this container
        let managedContext = appDelegate.persistentContainer.viewContext
        
        //Prepare the request of type NSFetchRequest  for the entity
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
        
//        fetchRequest.fetchLimit = 1
//        fetchRequest.predicate = NSPredicate(format: "username = %@", "Ankur")
//        fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "email", ascending: false)]
//
        do {
            let result = try managedContext.fetch(fetchRequest)
            for data in result as! [NSManagedObject] {
                print(data.value(forKey: "username") as! String)
            }
            
        } catch {
            
            print("Failed")
        }
    }

Update Data

To update a record, we first need to fetch or retrieve the data using a predicate, similar to the process mentioned above for retrieving data. Once we have retrieved the desired record, we can follow these steps to update it:

  • Prepare the request with predicate for the entity (User in our example)
  • Fetch record and Set New value with key
  • And Last Save context same as create data.
func updateData(){
    
        //As we know that container is set up in the AppDelegates so we need to refer that container.
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
        
        //We need to create a context from this container
        let managedContext = appDelegate.persistentContainer.viewContext
        
        let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "User")
        fetchRequest.predicate = NSPredicate(format: "username = %@", "Ankur1")
        do
        {
            let test = try managedContext.fetch(fetchRequest)
   
                let objectUpdate = test[0] as! NSManagedObject
                objectUpdate.setValue("newName", forKey: "username")
                objectUpdate.setValue("newmail", forKey: "email")
                objectUpdate.setValue("newpassword", forKey: "password")
                do{
                    try managedContext.save()
                }
                catch
                {
                    print(error)
                }
            }
        catch
        {
            print(error)
        }
   
    }

Delete Data

For delete record first we have to find object which we want to delete by fetchRequest. then follow below few steps for delete record

  • Prepare the request with predicate for the entity (User in our example)
  • Fetch record and which we want to delete
  • And make context.delete(object) call (ref image attached below)
func deleteData(){
        
        //As we know that container is set up in the AppDelegates so we need to refer that container.
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
        
        //We need to create a context from this container
        let managedContext = appDelegate.persistentContainer.viewContext
        
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
        fetchRequest.predicate = NSPredicate(format: "username = %@", "Ankur3")
       
        do
        {
            let test = try managedContext.fetch(fetchRequest)
            
            let objectToDelete = test[0] as! NSManagedObject
            managedContext.delete(objectToDelete)
            
            do{
                try managedContext.save()
            }
            catch
            {
                print(error)
            }
            
        }
        catch
        {
            print(error)
        }
    }

Download

CoreData Demo

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *