Database Reference
In-Depth Information
Success! The full list of World Cup participants is on your device or iOS Simulator.
Notice, however, that every country has zero wins and there's no way to increment
the score. Some people say that soccer is a low-scoring sport, but this is absurd!
Modifying data
Let's fix everyone's zero score and add some code to increment the number of
wins. Replace the currently empty implementation of the table view delegate
method
tableView(_:didSelectRowAtIndexPath:)
as shown below:
func
tableView(tableView:
UITableView
,
didSelectRowAtIndexPath indexPath:
NSIndexPath
) {
tableView.
deselectRowAtIndexPath
(indexPath, animated:
true
)
let
team =
fetchedResultsController
.
objectAtIndexPath
(indexPath)
as
Team
let
wins = team.
wins
.
integerValue
team.
wins
=
NSNumber
(integer: wins +
1
)
coreDataStack
.
saveContext
()
}
When the user taps on a row, you grab the
Team
that corresponds to the selected
index path, increment its number of wins and commit the change to Core Data's
persistent store.
Remember from earlier chapters that Core Data stores integers as
NSNumber
s, so
you have to unwrap the number of wins before you can modify it, and you have to
rewrap it before you can save it.
You might think a fetched
results
controller is only good for getting results, but the
Team
objects you get back are the same old managed object subclasses. You can
update their values and save just as you've always done.