Friday, July 21, 2017

Swift 3 - CoreData - CRUD Operations (Tutorial-1)

CoreData is a native iOS framework which works as a wrapper b/w iOS app and sqlite.

Though CoreData also stores data in a sqlite file, It is a powerful API which makes our CRUD operations on internal storage data very easy and handy by proving below features in the API.

  • Data models creations
  • Relationships creation
  • Delete rules/actions 
  • Version handling


In this tutorial I will explain the necessary stuff for simple CRUD operations by taking an example.

You can checkout the example from here.

Below things are must known for these CRUD operations

  • NSPersistentContainer
  • NSManagedObjectContext
  • NSEntityDescription
  • NSManagedObject


I am not going to explain what are those and the importance of those in this post. Please read out the comments in the code in the example link I have given. 

What we are going to save is, We are going to take person details(name and grade) from user and going to store, display, edit and delete using CoreData.





I have created Person entity and added attributes.





Please checkout the code to see how data is getting pushed to managedObjectContent and saving it will actually get stored in the sqlite file.

Grade is something we are saving in the entity called VIP which is a subclass of Person class just to show the subclassing of managed objects.









  @objc(Person)
   public class Person: NSManagedObject {    
   }

  @objc(VIP)
   public class VIP: Person {
   }




With my example, we can edit and delete also the saved user’s data.







One important point that I want to discuss here is, Whatever data changes(add/edit/delete) we make to our model objects,
We need to save the changes like shown below.


Editing Person data,




      func edit(person: NSManagedObject, with name: String, 
                 onCompletion: @escaping (_ person:NSManagedObject) -> Void, 
                 onFailure: @escaping (_ error: NSError) -> Void) {
    
        let managedContext = self.persistentContainer.viewContext
        
        (person as! Person).name = name
        (person as! Person).lastUpdated = Date() as NSDate?
        
        do {
        try managedContext.save()
            onCompletion(person)
        } catch let error as NSError {
            onFailure(error as NSError)
        }
    }




Deleting(soft/hard) Person data,




      func delete(person: NSManagedObject, onCompletion: 
                                              @escaping (_ status:Bool) -> Void) {
        let managedContext =     
               CoreDataManager.sharedInstance.persistentContainer.viewContext

        (person as! Person).active = false

        (person as! Person).lastUpdated = Date() as NSDate?

        do {
            try managedContext.save()
            onCompletion(true)
        } catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
        }

    }

    



In the next tutorial Let’s see some data validation stuff :)

Hope this post is useful. Feel free to comment incase of any queries.