Database Reference
In-Depth Information
}
The most significant change to these methods occurs in
cellForRowAtIndexPath
.
Instead of matching cells with the corresponding string in the model array, you now
match cells with the corresponding
NSManagedObject
.
Note how you grab the
name
attribute from the
NSManagedObject
. It happens here:
cell.
textLabel
.
text
= person.
valueForKey
(
"name"
)
as
String
Why do you have to do this? As it turns out,
NSManagedObject
doesn't know about
the
name
attribute you defined in your data model, so there's no way of accessing it
directly with a property. The only way Core Data provides to read the value is key-
value coding, commonly referred to as KVC.
Note:
If you're new to iOS development, you may not be familiar with key-
value coding or KVC.
KVC is a mechanism in Cocoa and Cocoa Touch for accessing an object's
properties indirectly using strings to identify properties. In this case, KVC
makes
NSMangedObject
behave more or less like a dictionary.
Key-value coding is available to all classes that descend from
NSObject
,
including
NSManagedObject
. You wouldn't be able to access properties using
KVC on a Swift object that doesn't descend from
NSObject
.
Next, replace the save action in the
addName
@IBAction
method with the following:
let
saveAction =
UIAlertAction
(title:
"Save"
,
style: .
Default
) { (action:
UIAlertAction
!) -> Void
in
let
textField = alert.
textFields
![
0
]
as
UITextField
self
.
saveName
(textField.
text
)
self
.
tableView
.
reloadData
()
}
This takes the text in the text field and passes it over to a new method called
saveName
. Add
saveName
to
ViewController.swift
, as shown below:
func
saveName(name:
String
) {
//1
let
appDelegate =
UIApplication
.sharedApplication().
delegate
as
AppDelegate
let
managedContext = appDelegate.
managedObjectContext
!