KVC和KVO的区别

KVC和KVO

KV表示的是key,value

C是Coding,O是Observing(监听)

建一个Person的类

person.h文件

 1 #import <Foundation/Foundation.h>
 2 #import "WuGong.h"
 3 
 4 @interface Person : NSObject
 5 {
 6     //NSString *_name;
 7     //NSString *name;
 8 }
 9 
10 @property (nonatomic,copy)NSString *name;
11 @property (nonatomic,strong)WuGong *wuGong;
12 //在Person类中定义一个wuGong的属性
13 @end

person.m文件

#import "Person.h"

@implementation Person
//没找到要赋值的key,就会调用,也是为了防止报错的时候程序会直接崩掉。
- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
    NSLog(@"没有找到%@",key);
}

- (id)valueForUndefinedKey:(NSString *)key
{
    NSLog( @"没有找到%@",key);
    return @"sdjfklsdj";
}
@end

ViewController.m文件

 1 #import "ViewController.h"
 2 #import "Person.h"
 3 
 4 @interface ViewController ()
 5 {
 6     Person *_person;
 7 }
 8 
 9 @end
10 
11 @implementation ViewController
12 
13 - (void)viewDidLoad
14 {
15     [super viewDidLoad];
17     
18     _person = [[Person alloc] init];
19     //_person.name = @"ymj";
20     //kvc赋值
21     [_person setValue:@"ldd" forKey:@"name"];
22     /*1.先找name的属性,找见赋值
23         2.如果name属性没找见,就找_name的成员变量赋值
24         3.如果_name 没有找到,就找name得成员变量赋值
25         4.如果都没有找到,就调用- (void)setValue:(id)value forKey:(NSString *)key方法
26      
27      */
28    
29     //kvc取值
30     //4.valueForUndefinedKey:
31     NSLog(@"%@",[_person valueForKey:@"name"]);
32     
33     //第二种赋值
34     _person.wuGong = [[WuGong alloc] init];
35     _person.wuGong.name = @"葵花点穴手";
36     [_person setValue:@"葵花点穴手" forKeyPath:@"wuGong.name"];
37     //第三种赋值
38     NSDictionary *dic = [NSDictionary dictionaryWithObject:@"紫萱" forKey:@"name"];
39     [_person setValuesForKeysWithDictionary:dic];
40     
41     
42     
43     //KVO
44     //self去监听——person里面的name有没有发生变化
45     NSString *str = @"李逍遥";
//因为context接收的时void类型,所以这里强转了一下
46 [_person addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:(void *)str]; 47 _person.name = @"龙葵"; 48 //移除监听 49 //[_person removeObserver:self forKeyPath:@""]; 50 } 51 52 //监听到值发生改变 keyPath:监听的属性@"name" Object:_person 53 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 54 { 55 NSString *str = (__bridge NSString *) context;//将接收的context值再转位NSString类型的 56 NSLog(@"%@",str); 57 NSLog(@"改变前的值:%@",change[@"old"]); 58 NSLog(@"改变后的值:%@",change[@"new"]); 59 }

WuGong.h文件

1 #import <Foundation/Foundation.h>
2 
3 @interface WuGong : NSObject
4 @property (nonatomic,copy)NSString *name;
5 @end

 

posted @ 2015-03-23 18:34  Angelone  阅读(157)  评论(0编辑  收藏  举报