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.



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


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.


Watch a document’s managedObjectContext


Merging changes

[iOS 7 Stanford 2013 Fall]Lecture 13 Core Data and Table View

Core Data and UITableView


  • Simply hooks an NSFetchedRequest up to a UITableViewController
  • Usually have an NSFetchedResultsController @property in UITableViewController
  • Use NSFetchedResultsController to answer all UITableViewDataSource protocol’s questions!

Sample Code

Very important method … objectAtIndexPath:

NSFetchedResultsController method…

Create a NSFetchedResultsController

  • Be sure that any cacheName is always associated with exactly the same request.
  • It is critical that the sortDescriptor matches up with the keyPath

NSFetchedResultsController Delegate

NSFRC also watches changes in Core Data and auto-updates table