iOS开发-5.KVC

2022-02-18  本文已影响0人  iOS_ZZ
a) KVC的全称是Key-Value Coding,俗称“键值编码”,可以通过一个key来访问某个属性
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; 
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"];
}
上一篇 下一篇

猜你喜欢

热点阅读