Lecture 12 Core Data

Core Data

How to get a NSManagedObjectContext

Create a UIManagedDocument and ask for its managedObjectContext.

Creating a UIManagedDocument

This only creates the UIManagedDocument instance, but does not open nor create the underlying file.

Open or create a UIManagedDocument

  1. First, check to see if the UIManagedDocument‘s underlying file exits on disk …

  2. … if it does, open the document using …

  3. … if it does not, create the document using …

  4. Completion handlers are needed because open/save is asynchronous !

Once document is open/created, start using it

Check the documentState when use it …

Other documentStates

  • UIDocumentStateClosed
  • UIDocumentStateSavingError
  • UIDocumentStateEditingDisabled
  • UIDocumentStateInConflict

Use document

Saving the document

  • UIManagedDocuments autosave themselves!
  • Save manually

  • This a UIKit class and so this method must be called on the main queue.

Closing the document

  • Will automatically close if there are no strong pointers left to it.
  • Close manually (asynchronous!) …

Inserting objects into the database

  • This NSEntityDescription class method returns an NSManagedObject instance.
  • All objects in the database are represented by NSManagedObject or subclasses thereof.
  • An instance of NSManagedObject is a manifestation of an Entity in our Core Data Model.
  • Attributes of a newly-inserted object will start out nil.

Deletion

Querying

Four important things involved in creating an NSFetchRequest

  1. Entity
  2. How many objects to fetch at a time and/or maximum to fetch
  3. NSSortDescriptors to specify the order in which the array of fetched objects are returned
  4. NSPredicate specifying which of those Entities to fetch

Creating an NSFetchRequest

NSSortDescriptor

Executing the fetch

  • Returns nil if there is an error (check the NSError for details)
  • Returns an empty array if there are no matches in the database.
  • Returns an NSArray of NSManagedObjects if there were any matches.

NSNotification

Watch a document’s managedObjectContext

NSManagedObjectContextDidSaveNotification

Merging changes