KVC(6) 验证属性

2020-02-01  本文已影响0人  yxibng

参考Validating Properties

validateValue:forKey:error:
validateValue:forKeyPath:error:
@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;

由于ioValueoutError都是引用类型,因此验证有3种可能的结果

  1. 认为 value 合法,返回 YES, 不修改value
  2. 认为 value 不合法,选择不修改 value, 返回 NO, 设置 error 的值
  3. 认为 value 不合法,创建一个新的 value, 返回 YES

自动验证

  1. Core Data automatically performs validation when the managed object context is saved
  2. Cocoa bindings allow you to specify that validation should occur automatically

关于手动验证的一些参考

iOS Property Validation Built on KVC

上一篇下一篇

猜你喜欢

热点阅读