KVC
Objective-C作為一門動(dòng)態(tài)語言痹届,NSObject 里面提供了動(dòng)態(tài)取設(shè)值的方法
- (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 鍵值編碼)
自己探究實(shí)現(xiàn)KVC
/*
通過 runtime objc_msgSend 向set 方法重發(fā)送消息
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 方法重發(fā)送消息
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;
}