validateValue:forKey:error:
validateValue:forKeyPath:error:
- 默认的实现会搜索对应对象的
validate<Key>:error:
方法 - 如果没有实现,默认成功,返回YES
- 如果实现了对应的方法,以方法的执行结果为准
@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@end
@implementation Person
- (BOOL)validateName:(inout id _Nullable __autoreleasing *)ioValue error:(out NSError *__autoreleasing _Nullable *)outError
{
id obj = *ioValue;
if ([obj isKindOfClass:NSString.class]) {
return YES;
}
*outError = [NSError errorWithDomain:NSArgumentDomain code:-1 userInfo:nil];
return NO;
}
@end
Validation of the name property
Person* person = [[Person alloc] init];
NSError* error;
NSString* name = @"John";
if (![person validateValue:&name forKey:@"name" error:&error]) {
NSLog(@"%@",error);
}
验证结果
- (BOOL)validateValue:(inout id _Nullable * _Nonnull)ioValue forKey:(NSString *)inKey error:(out NSError **)outError;
- (BOOL)validateValue:(inout id _Nullable * _Nonnull)ioValue forKeyPath:(NSString *)inKeyPath error:(out NSError **)outError;
由于ioValue
和 outError
都是引用类型,因此验证有3种可能的结果
- 认为 value 合法,返回 YES, 不修改value
- 认为 value 不合法,选择不修改 value, 返回 NO, 设置 error 的值
- 认为 value 不合法,创建一个新的 value, 返回 YES
自动验证
- Core Data automatically performs validation when the managed object context is saved
- Cocoa bindings allow you to specify that validation should occur automatically
网友评论