KVC
KVC的全稱是Key-Value Coding简卧,俗稱“鍵值編碼”,可以通過一個key來訪問某個屬性.
//API
- (void)setValue:(id)value forKeyPath:(NSString *)keyPath;
- (void)setValue:(id)value forKey:(NSString *)key;
- (id)valueForKeyPath:(NSString *)keyPath;
- (id)valueForKey:(NSString *)key;
KVC使用
//People類
@interface People : NSObject
@property(nonatomic, assign)int age;
@end
//main
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here..
People *p = [[People alloc] init];
[p setValue:@10 forKey:@"age"];
//[p setValue:@10 forKeyPath:@"age"];
NSLog(@"%d",p.age);
return 0;
}
}
可以看到打印都可以打印出10
KVC賦值過程
KVC賦值會觸發(fā)KVO
KVO原理類似以下操作:
1.KVO賦值操作(不管是不是調(diào)用set或者直接賦值)
2.willChangeValueForKey:
3.didChangeValueForKey:(內(nèi)部調(diào)用通知KVO方法)