Database Reference
In-Depth Information
Note:
Chapter 6, “Versioning and Migration,” covers
NSMigratePersistentStoresAutomaticallyOption
. For now, you just need to
know that setting this options tells Core Data to do its best to automatically
merge different versions of a managed object model when the model's entities
or attributes change.
Finally, under the initializer method, add the following method:
func
saveContext() {
var
error:
NSError
? =
nil
if
context
.
hasChanges
&& !
context
.
save
(&error) {
println
(
"Could not save:
\(error)
,
\(error?.
userInfo
)
"
)
}
}
This is a convenience method to save the stack's managed object context and
handle any errors that might result.
Switch to
ViewController.swift
and make the following changes. First, import the
Core Data framework below
import UIKit
:
import
CoreData
Then, add a property inside the class definition to hold the managed object context:
var
managedContext:
NSManagedObjectContext
!
As in the previous chapter, you'll follow the pattern of each view controller having a
reference to the managed object context.
Now open
AppDelegate.swift
and make the following changes. Again, you need to
import the Core Data framework below
import UIKit
:
import
CoreData
Then, below
var window: UIWindow?
,
add a variable to hold the Core Data stack:
lazy
var
coreDataStack = CoreDataStack()
You initialize the Core Data stack object as a lazy variable on the application
delegate. This means the stack won't be set up until the first time you access the
property.
Still in
AppDelegate.swift
, implement
application(_:didFinishLaunchingWithOptions:)
as shown below:
func
application(application:
UIApplication
,