views:

12

answers:

1

The docs say:

you should implement methods of the form validate:error:, as defined by the NSKeyValueCoding protocol

so lets say I have an attribute which is an int: friendAge

I want to make sure that any friend may not be younger than 30. So how would I make that validation method?

-validateFriendAge:error:

What am I gonna do in there, exactly? And what shall I do with that NSError I get passed? I think it has an dictionary where I can return a humanly readable string in an arbitrary language (i.e. the one that's used currently), so I can output a reasonable error like: "Friend is not old enough"... how to do that?

A: 

You can do anything you want in there. You can validate that the age is between ranges or any other logic you want.

Assuming there is an issue, you populate the error and have at least a value for the NSLocaliedDescriptionKey. That error will then be handed back to the UI or whatever this value is getting set from and allow you to handle the validation error. This means if there is other useful information you may need in the calling/setting method, you can add it into the NSError here and receive it.

For example:

-(BOOL)validateFreindAge:(NSNumber*)ageValue error:(NSError **)outError 
{
    if ([ageValue integerValue] <= 0) {
        NSString *errorDesc = @"Age cannot be below zero.";
        NSDictionary *dictionary = [NSDictionary dictionaryWithObject:errorDesc forKey:NSLocalizedDescriptionKey];
        *error = [NSError errorWithDomain:@"MyDomain" code:1123 userInfo:dictionary];
        return NO;
    }
    return YES;
}
Marcus S. Zarra