探索Objective-C的KVC实现

KVC

Objective-C作为一门动态语言,NSObject 里面提供了动态取设值的方法

- (nullable id)valueForKey:(NSString *)key;
- (void)setValue:(nullable id)value forKey:(NSString *)key;

- (nullable id)valueForKeyPath:(NSString *)keyPath;
- (void)setValue:(nullable id)value forKeyPath:(NSString *)keyPath;

- (nullable id)valueForUndefinedKey:(NSString *)key;
- (void)setValue:(nullable id)value forUndefinedKey:(NSString *)key;

这就是 KVC (全称 key valued coding 键值编码)

自己探究实现KVC

/*
 通过 runtime  objc_msgSend 向set 方法重发送消息
 model: set 方法
 */
- (void)jn_setValue:(id)value forKey:(NSString *)key {
    NSString *selName = [NSString stringWithFormat:@"set%@:",key.capitalizedString];
    SEL sel = NSSelectorFromString(selName);
    if (sel) {
        ((void(*)(id,SEL,id))objc_msgSend)(self,sel,value);
    }
}
/*
 通过 runtime  objc_msgSend 向get 方法重发送消息
 model: get 方法
 */
- (nullable id)jn_valueForKey:(NSString *)key {
    SEL getSel = NSSelectorFromString(key);
    NSString *value = ((id(*)(id,SEL,id))objc_msgSend)(self,getSel,@"v@:@");
    return value;
}

你可能感兴趣的:(探索Objective-C的KVC实现)