CoreData : Insert,update,delete,fetch data from the database

Posted By : Nitin Bhatt | 12-May-2016

In this example i have Created one Entity “EmployeeDetails”.

 

To create an entity,click the + button in the bottom-left of the editor view and name the entity “EmployeeDetails”

 

Once you create a entity, you need to add attributes to it , Click on the +button in the attributes section to do that. I have create the three entities id, name,contactNumber.

 

 

Create the subclass of NSManagedObject which is based on the entity defined in the XXX.xcdatamodel file

To create a file click on XXX.xcdatamodeld (Right Click) -> New File -> CoreData(iOS)  -> NSManagedObject subclass 

 

 

Insert Data in EmployeeDetails : -

    class func createInManagedObjectContext(id: String, name: String,contactNumber: String) -> EmployeeDetails {
        
        let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
        
        let newItem = NSEntityDescription.insertNewObjectForEntityForName("EmployeeDetails", inManagedObjectContext: managedObjectContext) as! EmployeeDetails
        
        newItem.id = id
        newItem.name = name
        newItem.contactNumber = contactNumber

        
        var error: NSError?
        do {
            try managedObjectContext.save()
        } catch let error1 as NSError {
            error = error1
            print("Could not save \(error), \(error?.userInfo)")
        }
        
        return newItem
    }
 

 

Fetch Data from EmployeeDetails : -

    class func fetchEmployeeDetails() -> [AnyObject] {
        var dataToReturn = [AnyObject]()
        var data = Dictionary < String , AnyObject >()
        let appDelegate =
            UIApplication.sharedApplication().delegate as! AppDelegate
        let managedContext = appDelegate.managedObjectContext
        let fetchRequest = NSFetchRequest(entityName:"EmployeeDetails")
        var error: NSError?
        
        do{
            let fetchedResults =
                try managedContext.executeFetchRequest(fetchRequest) as? [NSManagedObject]
            
            if let results = fetchedResults {
                for index in 0 ..< results.count {
                    let match = results[index] as NSManagedObject
                    data = ["id" : match.valueForKey("id") as! String,
                            "name" : match.valueForKey("name") as! String,
                            "contactNumber" : match.valueForKey("contactNumber") as! String,
                    ]
                    dataToReturn.append(data)
                }
            } else {
                print("Could not fetch \(error), \(error!.userInfo)")
            }
        } catch let error1 as NSError {
            error = error1
            print("Could not fetch \(error),\(error!.userInfo)")
        }
        return dataToReturn
    }
 

Update contactNumber in Employee Details :- 

    class func updateContactNumber(id:String,contactNumber:String){
        let appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
        let context: NSManagedObjectContext = appDel.managedObjectContext
        
        let request = NSFetchRequest(entityName: "EmployeeDetails")
        request.predicate = NSPredicate(format: "id = %@", id)
        
        if let fetchResults = (try? appDel.managedObjectContext.executeFetchRequest(request)) as? [NSManagedObject] {
            if fetchResults.count != 0{
                var managedObject = fetchResults as! [EmployeeDetails]
                
                managedObject[0].setValue(contactNumber, forKey: "contactNumber")
                
                do {
                    try context.save()
                } catch _ {
                }
            }
        }
    }
 

Delete Data from Employee Details : - 

     class func deleteEmployeeDetails() {
        let appDelegate =
            UIApplication.sharedApplication().delegate as! AppDelegate
        let fetchRequest = NSFetchRequest(entityName: "EmployeeDetails")
        if let fetchResults = (try? appDelegate.managedObjectContext.executeFetchRequest(fetchRequest)) as? [EmployeeDetails] {
            var preferncesData = fetchResults
            if preferncesData.count > 0{
                let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
                let context:NSManagedObjectContext = appDel.managedObjectContext
                for index in 0...preferncesData.count - 1{
                    context.deleteObject(preferncesData[index] as NSManagedObject)
                }
                preferncesData.removeAll(keepCapacity: false)
                do {
                    try context.save()
                } catch _ {
                }
            }
        }
    }
 

THANKS

 

About Author

Author Image
Nitin Bhatt

Nitin is an Assistant Project Manager specializing in iOS Application Development. He is an avid reader.

Request for Proposal

Name is required

Comment is required

Sending message..