美文网首页
探索Objective-C的KVC实现

探索Objective-C的KVC实现

作者: Jniying | 来源:发表于2019-07-26 11:51 被阅读0次

    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实现

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