标签:
NSString *name = [student valueForKey:@"name"];
valueForKey:首先查找以name或isName命名的getter方法,如果不存在getter方法,就在对象内部查找名为_name或name的实例变量
NSLog(@"age is %@", [student valueForKey:@"age"]);
NSLog中的%@输出一个对象,但age是一个int值,而不是对象,为什么会合理呢?原因如下:
使用valueForKey:时,KVC会自动将标量值(int、float、struct等)翻入NSNumber或NSValue中包装成一个对象,然后返回。因此,KVC有自动包装功能。
[student setValue:@"MJ" forKey:@"name"];
这个方法的工作方式和valueForKey:相同,首先查找setter方法,例如setName:,如果不存在setter方法,就在类中查找名为name或者_name的实例变量,然后为它赋值
[student setValue:[NSNumber numberWithInt:17] forKey:@"age"];
在设置一个标量值时,需要先将标量值包装成一个NSNumber或NSValue对象
NSArray *keys = [NSArray arrayWithObjects:@"name", @"age", nil];
NSDictionary *dict = [student dictionaryWithValuesForKeys:keys];
NSArray *keys = [NSArray arrayWithObjects:@"name", @"age", nil];
NSArray *values = [NSArray arrayWithObjects:@"MJ", [NSNumber numberWithInt:16], nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:values forKeys:keys];
[student setValuesForKeysWithDictionary:dict];
[student setValue:@"12345" forKeyPath:@"card.no"];
[student valueForKeyPath:@"card.no"];
NSNumber *count = [student.books valueForKeyPath:@"@count"]; 或者
NSNumber *count = [student valueForKeyPath:@"books.@count"];
NSNumber *sum = [student.books valueForKeyPath:@"@sum.price"]; 或者
NSNumber *sum = [student valueForKeyPath:@"books.@sum.price"];
NSArray *prices = [student.books valueForKeyPath:@"@distinctUnionOfObjects.price"];
或者
NSArray *prices = [student valueForKeyPath:@"books.@distinctUnionOfObjects.price"];
-(void)addObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context
anObserver :监听器对象
keyPath :监听的属性
options :决定了当属性改变时,要传递什么数据给监听器
-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context
keyPath :监听的属性
object :谁的属性改变了
change :属性改变时传递过来的信息(取决于添加监听器时的options参数)
-(void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath
标签:
原文地址:http://www.cnblogs.com/niexiaobo/p/4888736.html