Database Reference
In-Depth Information
Attribute validation is one of the few exceptions. If you add it to your app after
shipping, you don't have to version your data model. Lucky you!
But what does this do, exactly?
Validation kicks in immediately after you call
save
on your managed object context.
The managed object context checks with the model to see if any of the new values
conflict with the validation rules you've put in place.
If there's a validation error, the save fails. Remember that
NSError
pointer you pass
into the save method? Up until now, you've had no reason to do anything special if
there's an error. Validation changes that.
If the save fails, Core Data populates the
NSError
you pass in by reference and lets
you decide what to do. It's time to see this in action.
Build and run the app once more. Give the red bowtie a rating of 6 out of 5 and
save. A rather cryptic error message will spill out onto your console:
The
userInfo
dictionary that comes with the error contains all kinds of useful
information about why Core Data aborted your save operation. It even has a
localized error message that you can show your users, under the key
NSLocalizedDescription
: “The operation couldn't be completed.”
What you do with this error, however, is entirely up to you. Re-implement
updateRating
to handle the error appropriately:
func
updateRating(numericString:
String
) {
let
rating =
(numericString
as
NSString)
.
doubleValue
currentBowtie
!.
rating
=
NSNumber
.numberWithDouble(rating)
var
error:
NSError
?
if
!
self
.
managedContext
.
save
(&error) {
if
error!.
code
==
NSValidationNumberTooLargeError
||
error!.
code
==
NSValidationNumberTooSmallError
{
rate
(
currentBowtie
)
}