iOS开发之笔记摘录

iOS基础 之 KVC键值编码

2017-09-20  本文已影响60180人  平安喜乐698
目录


1. KVC键值编码(k:键 V:值 C:编码)

是一种通过属性名间接访问属性的方式。

NSObject(NSKeyValueCoding)分类中定义了KVC相关方法

使用

    PersonModel *personM=[PersonModel new];
    
    // 首先 查找set方法->若没有则查找变量->若还没有则调用setValueforUndefinedKey->若没实现setValueforUndefinedKey则崩溃
    [personM setValue:@"张三丰" forKey:@"name"];
    // 首先 查找get方法->若没有则查找变量->若还没有则调用valueforUndefinedKey->若没实现valueforUndefinedKey则崩溃
    NSString *name=[personM valueForKey:@"name"];

    // 多级路径
    [personM setValue:@"" forKeyPath:@"dog.name"];
    int dogAge=[personM valueForKeyPath:@"dog.age"];

注意

    当非类类型属性使用setValue设置为nil时会调用setNilValueForKey方法,并引发NSInvalidArgumentException导致崩溃
    [[Person new]setValue:nil forKey:@"likeNum"];
解决
    // 覆写这个空方法既可避免崩溃(给类类型设置nil不会调用该方法)
    -(void)setNilValueForKey:(NSString *)key{
    }
PersonModel.h
#import <Foundation/Foundation.h>
@interface PersonModel : NSObject
@property (nonatomic,copy) NSString *name;
@property (nonatomic,assign) int likeNum;
@end


PersonModel.m
#import "PersonModel.h"
@implementation PersonModel

// 初始化(用于将字典转换为模型)
-(instancetype)initWithDic:(NSDictionary *)dic{
    self=[super init];
    if(self){
        // 给模型所有属性赋值(等价于循环setValueForKey给属性赋值)
        [self setValuesForKeysWithDictionary:dic];
    }
    return self;
}

// 找不到键时调用
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{}

// 覆写以下方法 做额外操作 (一般不需要)
-(void)setValue:(id)value forKey:(NSString *)key{
    [super setValue:value forKey:key];
}
-(void)setValue:(id)value forKeyPath:(NSString *)keyPath{
    [super setValue:value forKeyPath:keyPath];
}
-(void)setValuesForKeysWithDictionary:(NSDictionary<NSString *,id> *)keyedValues{
    [super setValuesForKeysWithDictionary:keyedValues];
}
@end
上一篇 下一篇

猜你喜欢

热点阅读