Database Reference
In-Depth Information
let
result =
managedContext
.
executeFetchRequest
(dogFetch,
error: &error)
as
[
Dog
]?
if
let
dogs = result {
if
dogs.
count
==
0
{
currentDog
=
Dog
(entity: dogEntity!,
insertIntoManagedObjectContext:
managedContext
)
currentDog
.
name
= dogName
if
!
managedContext
.
save
(&error) {
println
(
"Could not save:
\(error)
"
)
}
}
else
{
currentDog
= dogs[
0
]
}
}
else
{
println
(
"Could not fetch:
\(error)
"
)
}
First, you fetch all
Dog
entities with names of “Fido” from Core Data. If the fetch
request comes back with zero results, this probably means it's the user's first time
opening the app. If this is the case, you insert a new dog, name it “Fido”, and set it
as the currently selected dog.
If the fetch request came back with results, you set the first entity (there should
only be one) as the currently selected dog.
Next, replace the implementation of
tableView(_:numberOfRowsInSection:)
with the
following:
func
tableView(tableView:
UITableView
,
numberOfRowsInSection section:
Int
) ->
Int
{
var
numRows =
0
if
let
dog =
currentDog
? {
numRows = dog.
walks
.
count
}
return
numRows;
}