Core Data with Swift in iOS App Development

October 19, 2017

Core Data is a framework which you can use to manage Data or Model

To work with following code, you need to create single view application.
Please select the core data check box when you create the project

Then you have the coredataex.xcdatamodeld to create the Entity and its attribute

Here I have created the User Entity and two attributes named firstname and lastname

How to Insert Data
You can write the following code inside the viewDidLoad() method

        let context =  (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        let user = User(context: context)
        user.firstname = "Mark"
        user.lastname = "Taylor"
        (UIApplication.shared.delegate as! AppDelegate).saveContext()

When you run the application it will insert the data into the database.

How to Retrieve Data
If you want to get data from the User entity you can use the following code

 
let context =  (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
   do{
        let rows = try context.fetch(User.fetchRequest()) as! [User]
        for row in rows{
            print(row.firstname!)
        }
    }catch{}

How to delete entry
If you want to delete a row you have to select that row first. I am using NSPredicate class to select the recods where firstname is equal to “Mark”
Once you select the row using context.fetch() you can use context.delete() to delete the record from the entity

    
        let userfecth: NSFetchRequest =  User.fetchRequest()
        userfecth.predicate = NSPredicate(format: "firstname == %@", "Mark")
        
        do{
            let rows = try context.fetch(userfecth)
            for row in rows{
                context.delete(row)
             }
            
        }catch{}
        
        (UIApplication.shared.delegate as! AppDelegate).saveContext()