Database Reference
In-Depth Information
var managedContext: NSManagedObjectContext !
To reiterate, before you can do anything in Core Data, you first have to get a
managed context to work on. Knowing how to propagate a managed context to
different parts of your app is an important aspect of Core Data programming.
Switch to AppDelegate.swift and replace didFinishLaunchingWithOptions (which
currently contains the test code) with the following implementation:
func application(application: UIApplication ,
didFinishLaunchingWithOptions
launchOptions: [ NSObject : AnyObject ]?) -> Bool {
let viewController =
self . window !. rootViewController as ViewController
viewController. managedContext = self . managedObjectContext
return true
}
In the previous chapter, you gained access to the app delegate's managed context
using the delegate more or less as a global variable. In this sample project, you'll
use another approach: pass the managed context from class to class via a property.
Since the caller is responsible for setting the managed context, ViewController can
use it without needing to know where it came from. The benefit here is cleaner
code since the context moves “down” the chain rather than each object accessing
some global state.
You've got seven bowties that are dying to enter your Core Data store. Satisfy them
by switching to ViewController.swift once again and adding the following two
methods:
//Insert sample data
func insertSampleData() {
let fetchRequest = NSFetchRequest (entityName: "Bowtie" )
fetchRequest. predicate = NSPredicate (
format: "searchKey != nil" )
let count = managedContext . countForFetchRequest (fetchRequest,
error: nil );
if count > 0 { return }
let path = NSBundle . mainBundle (). pathForResource ( "SampleData" ,
ofType: "plist" )
Search WWH ::




Custom Search