Database Reference
In-Depth Information
Saving to Core Data
Import the Core Data module at the top of
ViewController.swift
:
//Add below "import UIKit"
import
CoreData
You may have had to link frameworks manually in your project's Build Phases if
you've worked with Objective-C frameworks. In Swift, a simple
import
statement is
all you need to start using Core Data APIs in your code.
Next, replace the table view's model with the following:
//Change [String] to [NSManagedObject]
var
people = [
NSManagedObject
]()
You'll be storing
Person
entities rather than just names, so you rename the
Array
that serves as the table view's data model to
people
. It now holds instances of
NSManagedObject
rather than simple Swift strings.
NSManagedObject
represents a single object stored in Core Data—you must use it to
create, edit, save and delete from your Core Data persistent store. As you'll see
shortly,
NSManagedObject
is a shape-shifter. It can take the form of any entity in
your data model, appropriating whatever attributes and relationships you defined.
Since you're changing the table view's model, you must also replace both data
source methods you implemented earlier with the following to reflect these
changes:
//Replace both UITableViewDataSource methods
func
tableView(tableView:
UITableView
,
numberOfRowsInSection section:
Int
) ->
Int
{
return
people
.
count
}
func
tableView(tableView:
UITableView
,
cellForRowAtIndexPath
indexPath:
NSIndexPath
) ->
UITableViewCell
{
let
cell =
tableView.
dequeueReusableCellWithIdentifier
(
"Cell"
)
as
UITableViewCell
let
person =
people
[indexPath.
row
]
cell.
textLabel
!.
text
= person.
valueForKey
(
"name"
)
as
String
?
return
cell