Database Reference
In-Depth Information
currentBowtie
= bowties[
0
]
populate
(
currentBowtie
)
}
else
{
println
(
"Could not fetch
\(error)
,
\(error!.
userInfo
)
"
)
}
Keeping track of the currently selected bow tie is necessary to implement the Wear
and Rate buttons since these actions only affect the current bow tie.
Every time the user taps on Wear, the button executes the
wear
action method. But
wear
is empty at the moment. Implement it as shown below:
@IBAction
func
wear(sender:
AnyObject
) {
let
times =
currentBowtie
.
timesWorn
.
integerValue
currentBowtie
.
timesWorn
=
NSNumber
(integer: (times +
1
))
currentBowtie
.
lastWorn
=
NSDate
()
var
error:
NSError
?
if
!
managedContext
.
save
(&error) {
println
(
"Could not save
\(error)
,
\(error!.
userInfo
)
"
)
}
populate
(
currentBowtie
)
}
This method takes the currently selected bow tie and increments its
timesWorn
attribute by one. Since the
timesWorn
property is an
NSNumber
, you have to first
unbox the integer, increment it and wrap it up nicely into another
NSNumber
.
Then, you change the
lastWorn
date to today and save the managed context to
commit these changes to disk. Finally, you populate the user interface to visualize
these changes.
Run the application and tap
Wear
as many times as you'd like. It looks like you
thoroughly enjoy the timeless elegance of a red bow tie!