iOS Questions (Persistence & Databases)

 Core Data 

  1. Core Data is a framework used to save, track, modify and filter the data within iOS apps, however, Core Data is not a Database.
  2. It allows data organised by the relational entity–attribute model to be serialised into XML, binary, or SQLite stores.
  3. Core Data is using SQLite as its persistent store but the framework itself is not the database.
  4. Core Data is an ORM (Object Relational Model) which creates a layer between the database and the UI.
  5. It speeds-up the process of interaction as we don’t have to write queries, just work with the ORM and let ORM handles the backend.


Core Data stack

- Manage and persist your app’s model layer.

  • A stack contains all the Core Data components you need to fetch, create, and manipulate managed objects.

  • Core Data provides a set of classes that collaboratively support your app’s model layer: (through fetch , create, manipulate manage objects)

A Core Data stack is composed of the following objects: 

1. NSManagedObjectContext:


  • A managed object context that provides a scratch pad for managed objects.

  • The NSManagedObjectContext object manages a collection of model objects, instances of the NSManagedObject class
  • An instance of NSManagedObjectContext tracks changes to instances of your app’s types.
  • view context was associated with the main queue. 
  • To perform data processing on a background queue as it can be CPU intensive. Examples like importing JSON into Core Data could otherwise block the view context and result in unresponsiveness in the user interface.

    The solution is to make use of a background managed object context. The latest APIs make it easy to create a new context from your persistent container:

  • let backgroundContext = persistentContainer.newBackgroundContext()
  • persistentContainer.performBackgroundTask { (backgroundContext) in
        // .. Core Data Code
    }

NSManagedObjectModel is a database schema that describes the application's entities. It defines the structure of the managed objects. 
The managed object model, an instance of the NSManagedObjectModel class, loads the data model and exposes it to the Core Data stack.

To generate the class file initially: Choose Editor > Create NSManagedObject Subclass from the menu at the top of the screen. Select your data model, then the appropriate entity, and choose where to save the files. Xcode places both class and properties files into your project.

3. NSPersistentStoreCoordinator

  • The persistent store coordinator ( NSPersistentStoreCoordinator ) is the intermediary between the actual files that object data is stored in and the object model that the app interacts with.
  • An instance which saves and fetches instances of your app’s types from stores.
  • It has a reference to a managed object model that describes the entities in the store or stores it manages. The coordinator is the central object in a Core Data stack.

Persistent store : persistent store is a repository in which managed objects may be stored. You can think of a persistent store as a database data file where individual records each hold the last-saved values of a managed object. Core Data offers three native file types for a persistent store: binary, XML, and SQLite.


/* code


func saveContext () {

        let context = persistentContainer.viewContext //NSManagedObjectContext

        if context.hasChanges {

            do {

                try context.save()

            } catch {

                let nserror = error as NSError

                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")

            }

        }

    }



*/


- An instance of NSPersistentContainer includes all objects needed to represent a functioning Core Data stack, and provides convenience methods and properties for common patterns.

NSPersistentContainer: 

  • A container that encapsulates the Core Data stack in your app.
  • Inside AppDelegate.swift there is a propery called 'persistentContainer', this is used to assign data model file like CoreDataSample.xcdatamodeld.
  • It Load stores from the storeDescriptions property that have not already been successfully added to the container. The completion handler is called once for each store that succeeds or fails.
  • The AppDelegate.swift file will have Core Data Stack code inside the file



      /* 

        let container = NSPersistentContainer(name: "coreDataSample")

          //coreDataSample.xcdatamodeld


        container.loadPersistentStores(completionHandler: { (storeDescription, error) in 


         }

      */




  


Comments

Popular posts from this blog

iOS Questions (Swift Programming Language)

Dispatch techniques: Dynamic dispatch and Static Dispatch

What’s the difference between var and let? Which one would you choose for properties in a struct and Class why?