探索Objective-C的KVC实现

2019-07-26  本文已影响0人  Jniying

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;
}
上一篇下一篇

猜你喜欢

热点阅读