1、KVC,即是指
Demo:
@interfacemyPerson : NSObject
{
}@end
@interfacetestViewController :UIViewController
@property(nonatomic, retain)myPerson*testPerson;
@end
-(void)testKVC
{
testPerson= [[myPerson alloc]init];
[testPersonsetValue:[NSNumbernumberWithInt:168]forKey:@"height"];
}
第一段代码是定义了一个myPerson的类,这个类有一个_height的属性,但是没有提供任何getter/setter的访问方法。同时在testViewController这个类里面有一个myPerson的对象指针。
2015-3-1311:16:21.970 test[408:c07] testPerson‘s init height = 0
2015-3-1311:16:21.971 test[408:c07] testPerson‘s height = 168
-(id)valueForKey:(NSString *)key; -(void)setValue:(id)valueforKey:(NSString *)key;
valueForKey的方法根据key的值读取对象的属性,setValue:forKey:是根据key的值来写对象的属性。
注意:
(1).key的值必须正确,如果拼写错误,会出现异常
(2).当key的值是没有定义的,valueForUndefinedKey:这个方法会被调用,如果你自己写了这个方法,key的值出错就会调用到这里来
(3).因为类key反复嵌套,所以有个keyPath的概念,keyPath就是用.号来把一个一个key链接起来,这样就可以根据这个路径访问下去
(4).NSArray/NSSet等都支持KVC
2、KVO的是KeyValueObserve的缩写,中文是键值观察。这是一个典型的观察者模式,观察者在键值改变时会得到通知。iOS中有个Notification的机制,也可以获得通知,但这个机制需要有个Center,相比之下KVO更加简洁而直接。
Demo:
- @interface
myPerson : NSObject - {
-
NSString *_name; -
int _age; -
int _height; -
int _weight; - }
- @end
-
- @interface
testViewController : UIViewController - @property
(nonatomic, retain) myPerson *testPerson; -
- -
(IBAction)onBtnTest:(id)sender; - @end
-
- -
(void)testKVO - {
-
testPerson = [[myPerson alloc] init]; -
-
[testPerson addObserver:self forKeyPath:@"height" options:NSKeyValueObservingOptio nNew context:nil]; - }
-
- -
(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context - {
-
if ([keyPath isEqualToString:@"height"]) { -
NSLog(@"Height is changed! new=%@", [change valueForKey:NSKeyValueChangeNewKey]); -
} else { -
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; -
} - }
-
- -
(IBAction)onBtnTest:(id)sender { -
int h = [[testPerson valueForKey:@"height"] intValue]; -
[testPerson setValue:[NSNumber numberWithInt:h+1] forKey:@"height"]; -
NSLog(@"person height=%@", [testPerson valueForKey:@"height"]); - }
-
- -
(void)dealloc - {
-
[testPerson removeObserver:self forKeyPath:@"height" context:nil]; -
[super dealloc]; - }
第一段代码声明了myPerson类,里面有个_height的属性。在testViewController有一个testPerson的对象指针。
3、NSNotification的用法见http://blog.youkuaiyun.com/eduora_meimei/article/details/44198909
区别:
delegate
notification的
KVO的
1.
delegate方法比notification更加直接,最典型的特征是,delegate方法往往需要关注返回值,也就是delegate方法的结果。比如-windowShouldClose:,需要关心返回的是yes还是no。所以delegate方法往往包含should这个很传神的词。也就是好比你做我的delegate,我会问你我想关闭窗口你愿意吗?你需要给我一个答案,我根据你的答案来决定如何做下一步。相反的,notification最大的特色就是不关心接受者的态度,我只管把通告放出来,你接受不接受就是你的事情,同时我也不关心结果。所以notification往往用did这个词汇,比如NSWindowDidResizeNotific
2、KVO和NSNotification的区别:
和delegate一样,KVO和NSNotification的作用也是类与类之间的通信,与delegate不同的是1)这两个都是负责发出通知,剩下的事情就不管了,所以没有返回值;2)delegate只是一对一,而这两个可以一对多。这两者也有各自的特点。
文章摘自 :http://www.mamicode.com/info-detail-515516.html