KVO 和 KVC

1、KVC

NSKeyValueCoding,即键值编码

//常用的 setter、getter 方式
        Person *p = [[Person alloc] init];
        p.name = @"张三";  //setter
        p.age = 20;  //setter 
        NSString *name = p.name; //getter
        Int age= p.age;//getter
  
等价于
//KVC 方式赋值
    [p setValue:@"张三" forKey:@"name"];
    [p setValue:@20 forKey:@"age"];

   NSString *name =[p valueForKey:@"name"];
   Int age= [p valueForKey:@"name"].int; 

2、KVO

KeyValue Observe,即键值观察。观察者模式

//添加观察者
        Person *p = [[Person alloc] init];
        p.name = @"张三";  //setter
        [p addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil]; 
        p.name = @"李四";  //通知改变
       
//如果观察的值有改变,得调用下面的方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context  
{  
    if ([keyPath isEqualToString:@"name"]) {  
         //name被改变了 
    } 
}

//记得销毁观察者
- (void)dealloc  
{  
    [p removeObserver:self forKeyPath:@"name" context:nil];  
}  

你可能感兴趣的:(KVO 和 KVC)