Search code examples
objective-cxcodecocoa-bindingskey-value-coding

How to implement Key Value Coding Validation


I have an ArrayController bound to a master/detail UI which is working just great. I'm now trying to implement validation at the model level.

Apple docs indicate the follow should work to validate individual properties:

-(BOOL)validateName:(id *)ioValue error:(NSError * __autoreleasing *)outError

So if I have a model property of "ProjectName", the following should automatically fire:

-(BOOL)validateProjectName:(id *)ioValue error:(NSError * __autoreleasing *)outError

But unfortunately, it just doesn't happen :(

However, interestingly, if I use the "catch all" method as below, it DOES work:

-(BOOL)validateValue:(inout __autoreleasing id *)ioValue forKey:(NSString *)inKey error:(out NSError *__autoreleasing *)outError  {

Within the method I can code to determine which property is being validated of course, but I can't figure out why it completely ignores the accessor method?

Can anyone shed any light on this?


Solution

  • The validation method does not automatically fire - from your linked documentation:

    In general, key-value coding does not perform validation automatically—it is your application’s responsibility to invoke the validation methods.

    And also:

    You can call validation methods directly, or by invoking validateValue:forKey:error: and specifying the key. The default implementation of validateValue:forKey:error: searches the class of the receiver for a validation method whose name matches the pattern validate:error:. If such a method is found, it is invoked and the result is returned. If no such method is found, validateValue:forKey:error: returns YES, validating the value.

    Which explains your second situation.