iOS开发-5.KVC

  • 1.什么是KVC?
a) KVC的全称是Key-Value Coding,俗称“键值编码”,可以通过一个key来访问某个属性
  • 2.常见的API有?
a) - (void)setValue:(id)value forKeyPath:(NSString *)keyPath; // keyPath:路径,一层一层找下去

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

c) - (id)valueForKeyPath:(NSString *)keyPath;

d) - (id)valueForKey:(NSString *)key; 
  • 3.setValue:forKey:的原理?

  • 4.valueForKey:的原理?

  • 5.person.age 和 [person setValue:@10 forKey:@"age"] 区别?或者提问通过kVC修改属性会触发KVO么?

a) 会触发

b) void test()
{
    MJObserver *observer = [[MJObserver alloc] init];
    MJPerson *person = [[MJPerson alloc] init];
    
    // 添加KVO监听
    [person addObserver:observer forKeyPath:@"age" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];
    
    // 通过KVC修改age属性
    [person setValue:@10 forKey:@"age"];
    // [person willChangeValueForKey:@"age"];
    // person->_age = 10;
    // [person didChangeValueForKey:@"age"];
    
    // 移除KVO监听
    [person removeObserver:observer forKeyPath:@"age"];
}

你可能感兴趣的:(iOS开发-5.KVC)