Insert and Delete from an Entity using Core Data in Swift

Posted By : Akshay Luthra | 30-Sep-2015

This blog is in continuation of my blog how to create an Entity using Core Data in Swift. Before reading this blog, I prefer you to have a look to it.

You can also read my blog on Fetch data from an Entity using Core Data in Swift.

 

In the “UserInfo.swift” file that I created in my previous blog, make two protocols. One for inserting the data and the other to delete the data.

 (If your background is Java, then you can relate a Protocol in Swift with an Interface in Java)

 

Now you have to give the body of the protocols you have made so that you can use them.

For this create “UserInfoServices.swift” file

 

Then, import the CoreData and make a class “UserInfoServices” that extends the UserInfoProtocol and write the insertion and deletion of data logics in the class by making functions.

 

import Foundation
import CoreData
import UIKit

class UserInfoServices:UserInfoProtocol{
    
    //Insert values in User Info table
    func insertUserInfoData()->UserInfo {
     
        let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
        let newItem = NSEntityDescription.insertNewObjectForEntityForName("UserInfo", inManagedObjectContext: managedObjectContext!) as! UserInfo
        newItem.userId="1"
        newItem.name="Demo User"
        
        var error: NSError?
        if !managedObjectContext!.save(&error) {
            println("Could not save \(error), \(error?.userInfo)")
        }
        return newItem
    }
    
    //Delete values from User Info table
    func deleteUserInfoData() {
        let appDelegate =
        UIApplication.sharedApplication().delegate as! AppDelegate
        let managedContext = appDelegate.managedObjectContext!
        let fetchRequest = NSFetchRequest(entityName: "UserInfo")
        fetchRequest.includesPropertyValues = false // Only fetch the managedObjectID (not the full object structure)
        if let fetchResults = managedContext.executeFetchRequest(fetchRequest, error: nil) as? [UserInfo] {
            for result in fetchResults {
                managedContext.deleteObject(result)
            }
        }
        var err: NSError?
        if !managedContext.save(&err) {
            println("User Info deleteData - Error : \(err!.localizedDescription)")
            abort()
        } else {
            println("User Info deleteData - Success")
        }
    }
    
}


 

 

THANKS

About Author

Author Image
Akshay Luthra

Akshay Luthra has excellent experience in developing Cross Platform Mobile Apps using JavaScript and Titanium Framework. He loves listening to music and travelling new places.

Request for Proposal

Name is required

Comment is required

Sending message..