Swift iOS Tutorial – Core Data – Add Update Delete

Core Data is an object graph and persistence framework provided by Apple in the Mac OS X and iOS operating systems. It was introduced in Mac OS X 10.4 Tiger and iOS with iPhone SDK 3.0.

Reference: https://en.wikipedia.org/wiki/Core_Data

Core Data

Core Data

Here I show some useful core data queries below (before that you need to create a model):

import UIKit
import CoreData

@objc(Entityones)
class Entityones: NSManagedObject {

@NSManaged var attribute_one: String
@NSManaged var attribute_two: String
@NSManaged var attribute_three: String

}

Core Data queries.

Create/Add query

let appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
        
        let context: NSManagedObjectContext = appDel.managedObjectContext!
        let en = NSEntityDescription.entityForName("Entityones", inManagedObjectContext: context)

        var newEn =  Entityones(entity: en!, insertIntoManagedObjectContext: context)
            
        newEn.attribute_one = "param1"
        newEn.attribute_two = "param2"
        newEn.attribute_three = "param3"
        
        context.save(nil)

Update query

let appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
                        let context: NSManagedObjectContext = appDel.managedObjectContext!
                        
                        let request = NSFetchRequest(entityName: "Entityones")
                        request.predicate = NSPredicate(format: "attribute1 = %@", "param1")
                        
                        if let fetchResults = appDel.managedObjectContext!.executeFetchRequest(request, error: nil) as? [NSManagedObject] {
                            if fetchResults.count != 0{
                                
                                var managedObject = fetchResults[0]
                                managedObject.setValue("param1", forKey: "attribute_one")
                                managedObject.setValue("param2", forKey: "attribute_two")
                                managedObject.setValue("param3", forKey: "attribute_three")
                                
                                context.save(nil)
                             }
                        }

Delete query

//use on UITableView
var myList: Array <AnyObject> = []

let appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
            let context: NSManagedObjectContext = appDel.managedObjectContext!
            context.deleteObject(myList[indexPath.row] as! NSManagedObject)
            myList.removeAtIndex(indexPath.row)
            context.save(nil)

If you want know more details how to integrate these queries to your application, feel free to drop your email here, nurdinnorazanservices@gmail.com.

2 thoughts on “Swift iOS Tutorial – Core Data – Add Update Delete

Leave a Reply

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