美文网首页程序员
iOS KVC赋值取值过程和异常处理

iOS KVC赋值取值过程和异常处理

作者: wp_Demo | 来源:发表于2019-01-09 16:53 被阅读0次
赋值过程:
  1. 先找相关方法:set<key>:,_set<key>:,setIs<key>:
  2. 若没有相关方法则:+ (BOOL)accessInstanceVariablesDirectly判断是否可以直接访问成员变量
  3. 如果accessInstanceVariablesDirectly返回YES,继续找相关成员变量_<key>,_is<key>,<key>,is<key>,如果没找到则抛出异常setValue: forUndefinedKey:
  4. 如果accessInstanceVariablesDirectly返回NO,直接执行KVC的setValue: forUndefinedKey:
取值过程:

1 .先找相关方法:get<key>:,<key>:
2 .若没有相关方法则:+ (BOOL)accessInstanceVariablesDirectly判断是否可以直接访问成员变量
3 .如果accessInstanceVariablesDirectly返回YES,继续找相关成员变量_<key>,_is<key>,<key>,is<key>,如果没找到则抛出异常valueForUndefinedKey:
4 .如果accessInstanceVariablesDirectly返回NO,直接执行KVC的valueForUndefinedKey:

赋值的时候要注意:

1:非对象类型的属性,赋值的时候,值不可以为空,否则会爆报:setNilValueForKey错误,为了解决赋值为空的报错,需要写下setNilValueForKey方法,不至于崩溃

@implementation Person
//非对象类型,值不能为空
- (void)setNilValueForKey:(NSString *)key{
    NSLog(@"setNilValueForKey :%@",key);
}
@end

2:对不存在的属性赋值会报错:setValue:forUndefinedKey:

-(void)setValue:(id)value forUndefinedKey:(NSString *)key
{
    NSLog(@"%@不存在",key);
}
赋值前验证值的合法性:
- (BOOL)validateValue:(inout id  _Nullable __autoreleasing *)ioValue error:(out NSError * _Nullable __autoreleasing *)outError{

validate<value>工作原理:
  1. 先找一下你的类中是否实现了方法validate<Value>:error:
  2. 如果实现了就会根据实现方法里面的自定义逻辑返回NO或者YES,如果没有实现这个犯法,则系统默认返回YES

比如我们设置人的年龄不能超过200岁,可以有如下判断:

- (BOOL)validateAge:(inout id  _Nullable __autoreleasing *)ioValue error:(out NSError * _Nullable __autoreleasing *)outError{
    NSNumber *value = (NSNumber*)*ioValue;
    int age = [value intValue];
    if (age <= 0 || age >= 200) {
        return NO;
    }
    return YES;
}

相关文章

网友评论

    本文标题:iOS KVC赋值取值过程和异常处理

    本文链接:https://www.haomeiwen.com/subject/rnckrqtx.html