I was fortunate to attend the iPhone Tech Talk conference, hosted by Apple Inc. in San Jose last October, 2009. One of the sessions I attended was on Core Data. At a very high level, Core Data is an Apple™ software framework for storing data on the computer - namely, the iPhone and the Mac. Please note that I don't plan on covering database design theory in this post so I'm assuming a familiarity with it.Core data is an Object graph management and persistence framework. Core data maintains a graph of objects (otherwise known as a managed object graph or managed object context). References to managed objects are stored in the object graph. Core Data serializes these objects and persists them to a data store. Core data can use several different underlying data stores - xml, binary, sqlite. The managed object context is a key concept in Core Data, as it provides a proxy between the application objects and the underlying data store(s). The persistent store coordinator is responsible for managing the relationship between the managed object context and the persistent store(s). A managed object context wraps a collection of managed objects and sits on top of a persistent store coordinator which houses one or more persistent stores. A managed object context is created via an instance of the NSManagedObjectContext class.
After working with Core Data, it is a worthwhile exercise to open the core data sqlite file and dig through the tables. A quick look through the tables will explain how Apple is handling referential integrity. The Core Data sqlite file is "not meant" to be accessed directly from within code. Do not modify it or attempt to write queries against it. There is no guarantee that the schema will not change. Core Data is meant to abstract implementation dependent details (i.e. the implementation may change upon any future releases).
The following notes were derived from three sources: Apple WWDC 2009, the iPhone Core Data session in San Jose last October, and my experience working with object/relational databases.
Creating a Core Data Stack
- Load the Data Model
- Create the persistent store coordinator and set the model
- Add the data store
- Create a managed object context and set the persistent store coordinator
Core Data Model
- A Core Data model does not need to be normalized. Define data contracts early on. Don't over tighten the data model - design with usage patterns in mind. Define entities or tables with Xcode's visual editor. (core data objects represent rows in these tables). In other words, a Core Data object (row of data) of type PERSON is an instance of the PERSON entity in the Core Data model. Of course, a person object will have relationships with other objects in the database. A Core Data Managed object context manages these objects, their relationships, and persists them to the underlying data store (via the persistent store coordinator). Core Data is simple to setup. Don't complicate it.
- NSManagedObjectContext defines the verbs (CRUD or fetch/insert/delete/save) that act on managed objects (nouns)
- NSManagedObjectContext tracks changes to properties in the data model
- Core Data fits very well in the MVC architecture.
- An NSPersistentStoreCoordinator can have multiple persistent stores(NSPersistentStore) and multiple Managed Object Contexts can use a single NSPersistentStoreCoordinator
- It is possible to delete the sqlite store file if the stored data needs to be deleted. This file is stored in $HOME/Library/Application Support/iPhone Simulator/User/Applications/SOMEAPPLICATIONGUID/Documents
- Use Core Data migration or built-in versioning for model changes. easy to use. zero code.
- Core data assigns one managed object context per thread; use notifcations for changes made to managed objects within a managed object context.
- never pass managed objects between threads, pass object IDs (actually the primary key)
- within a thread, create a new Managed object context and then tell the new Managed object context what objects IDs to fetch
- Use NSFetchedResultsController (break up fetches into sections) - it is fast, efficient, and easy.
- Create an NSFetchedResultsController
- Set the fetch request, predicate, and sort descriptors. fetch request provides predicate and sort descriptors). fetch request and predicate are immutable.
- the keypath returns the section name (section information is cached)
- set yourself as its delegate and implement your tableview methods
- Create separate controllers for different data sets
- set the entity that you want to fetch against
- create NSEntityDescription - provide managed object context and entity you want to work with
- set the predicate (if applicable)
- Fetch - pass in fetch and error
- setup fetch request (only need some of the objects at a time so setBatchSize:)
- set batch size
- you get back an NSArray of results
- use setRelationshipKeyPathsForPrefetching:
Managed Object Interaction
- Use accessors
- Objective-C properties
- To Many relationships are sets
- NSManagedObjects provides Key value coding/observing out of the box
- Managed Object Context observes object changes. Leverage change tracking notifcations
- Register for Object Level Changes (KVO)
- Register for Graph Level Changes (NSNotifications)