Database Reference
In-Depth Information
//2
let
entity =
NSEntityDescription
.entityForName(
"Person"
,
inManagedObjectContext:
managedContext)
let
person =
NSManagedObject
(entity: entity!,
insertIntoManagedObjectContext:managedContext)
//3
person.
setValue
(name, forKey:
"name"
)
//4
var
error:
NSError
?
if
!managedContext.
save
(&error) {
println
(
"Could not save
\(error)
,
\(error?.
userInfo
)
"
)
}
//5
people
.
append
(person)
}
This is where Core Data kicks in! Here's what the code does:
1. Before you can save or retrieve anything from your Core Data store, you first
need to get your hands on an
NSManagedObjectContext
. You can think of a
managed object context as an in-memory “scratchpad” for working with managed
objects.
Think of saving a new managed object to Core Data as a two-step process: first,
you insert a new managed object into a managed object context; then, after
you're happy with your shiny new managed object, you “commit” the changes in
your managed object context to save it to disk.
Xcode has already generated a managed object context as part of the new
project's template - remember, this only happens if you check the
Use Core
Data
checkbox at the beginning. This default managed object context lives as a
property of the application delegate. To access it, you first get a reference to the
app delegate.
2. You create a new managed object and insert it into the managed object context.
You can do this in one step with
NSManagedObject
's designated initializer:
init(entity:insertIntoManagedObjectContext:)
.
You may be wondering what an
NSEntityDescription
is all about. Recall that
earlier, I called
NSManagedObject
a “shape-shifter” class because it can represent
any entity. An entity description is the piece that links the entity definition from
your data model with an instance of
NSManagedObject
at runtime.