Skip to content
Kevin Leong edited this page Jan 23, 2017 · 8 revisions

Core Data

Initializing the Core Data Stack

/**
        Combines all models in the specified list of bundles and returns
        a consolidated model.

        If nil is supplied, then only the main bundled is searched.
     */
    NSManagedObjectModel *managedObjectModel =
        [NSManagedObjectModel mergedModelFromBundles:nil];

    // Create the persistent store coordinator.
    NSPersistentStoreCoordinator *storeCoordinator =
        [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];

    /**
     Create the managed object context for use on the Main Queue.
     */
    NSManagedObjectContext *objectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    objectContext.persistentStoreCoordinator = storeCoordinator;

    /**
        NSFileManager provides an abstraction layer on top of UNIX and finder
        commands that allows for CRUD operations on files.
     */
    NSFileManager *fileManager = [NSFileManager defaultManager];

    /**
        Returns a list of URLs for the user's document directory within the
        current app's sandbox.
     */
    NSArray<NSURL *> *documentsUrls = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];

    // documentUrls will return an array of 1, so use that as the URL.
    NSURL *documentsUrl = [documentsUrls firstObject];

    // Append the desired file name and extension.
    NSURL *storeUrl = [documentsUrl URLByAppendingPathComponent:@"ExerciseOne.sqlite"];

    // Clears any existing data in the database if necessary if uncommented.
    // [[NSFileManager defaultManager] removeItemAtURL:storeUrl error:nil];

    NSError *error = nil;

    /**
        Include this to disable Write-Ahead Logging (WAL), which is the default
        for SQLite in iOS.

        Disabling WAL saves all changes to the *.sqlite file, which can then
        be read by a SQLite viewer.

        If viewing the SQLite DB via a viewer is not necessary, then comment
        out the line below.
     */
    NSDictionary *options = @{NSSQLitePragmasOption: @{@"journal_mode": @"DELETE"}};

    /**
     Adds a new store to the persistent store coordinator.
     */
    NSPersistentStore *store =
        [
            storeCoordinator
            // Possible types: in memory DB, SQLite, XML
            addPersistentStoreWithType:NSSQLiteStoreType
            configuration:nil
            URL:storeUrl // Store file location
            // Dictionary specifying options.  E.g., read-only.
            options:options
            error : &error
        ];

    NSAssert(
             store != nil,
             @"Error initializing persistent store coordinator: %@\n%@",
             [error localizedDescription], [error userInfo]
             );

References

Core Data Objects

NSEntityDescription

Describes an entity, which includes its attributes and relationships.

Each NSEntityDescription is associated with multiple NSPropertyDescription objects, each which define the properties for an entity.

Properties are are to entities what instance variables are to classes.

Relationships are defined by NSRelationshipDescription : NSPropertyDescription objects, which are also associated with an entity.

NSManagedObjectModel

Contains a collection of entities. This is essentially the schema for a core data stack.

At build time, all .xcdatamodel files are compiled into a .momd file, which is used to initialize the managed object model instance.

NSPersistentStoreCoordinator

In a Core Data stack, the NSPersistentStoreCoordinator is the object that connects entities in the model to their persisted counterparts.

The persistent store coodinator does the following:

  • It allows multiple stores to appear like a single store.
  • Allows NSManagedObjectContext objects to access the managed object model.
  • Used by NSManagedObjectContext objects to fetch and persist data.

NSManagedObjectContext

An NSManagedObjectContext instance can be thought of as a scoped space for NSManagedObject instances.

Copies of a NSMangedObject may exist across multiple contexts, but instances are unique to a single context.

NSManagedObjectContext instances are used frequently to perform the following:

  • Retrieving and saving objects to and from a persistent store.
  • Observing changes in objects.
  • Allows undo or redo operations.

Context Concurrency

NSManagedObjectContext objects are also confined to the thread that they are initialized on or specified with.

When a context needs to be accessed on a different thread than it is meant to run on, the persistent store coordinator should be passed to the new thread, and the thread should be responsible for creating the NSManagedObjectContext.

NSFetchRequest

NSFetchedRequestController

Viewing SQL Debug Statements

Add the following to the launch arguments for the debug -com.apple.CoreData.SQLDebug 3.

The higher the number, the more verbose the logging level. Values range from 1 to 3.

Launch arguments can be found via Product > Scheme > Edit Scheme

Making changes to Core Data Models

References

References

Clone this wiki locally