1、KVC琅攘,即是指 NSKeyValueCoding垮庐,一個(gè)非正式的Protocol,提供一種機(jī)制來間接訪問對象的屬性坞琴。而不是通過調(diào)用Setter哨查、Getter方法訪問。KVO 就是基于 KVC 實(shí)現(xiàn)的關(guān)鍵技術(shù)之一置济。(關(guān)鍵點(diǎn):訪問對象的屬性=馇 )
例子:
//定義一個(gè)Person類 ?有兩個(gè)屬性name 和 age
@interface Person : NSObject
{
NSString*_name;
int????? _age;
} @end
//定義一個(gè)viewController 用來測試(如果你已經(jīng)學(xué)到UI階段就用viewController,如果沒學(xué)到就在main函數(shù)里面實(shí)現(xiàn))
#import "Person.h"
@interface ViewController :UIViewController
@property (nonatomic, retain) Person* testPerson;
@end
- (void)viewDidLoad {
? ? ? [superviewDidLoad];
//創(chuàng)建Person對象
? ? ? testPerson = [[myPerson alloc] init];
//設(shè)置age屬性的值
? ? ? [testPerson setValue:[NSNumber ?numberWithInt:18] ?forKey:@"age"];??
//獲取age的值
? ? ? NSLog(@"testPerson‘s age = %@", ? ? ?[testPerson valueForKey:@"age"]);
}
就這兩個(gè)方法:
?- (id)valueForKey:(NSString *)key; ? ? ? ? ?
-(void)setValue:(id)value forKey:(NSString *)key;
key是要設(shè)置的age屬性浙于,value 是age的值
2护盈、KVO的是KeyValue Observe的縮寫,中文是鍵值觀察羞酗。這是一個(gè)典型的觀察者模式腐宋,觀察者在鍵值改變時(shí)會得到通知。
設(shè)置就3步:
1.注冊需要觀察的對象的屬性addObserver:forKeyPath:options:context:(一般添加self為觀察者)
2.實(shí)現(xiàn)observeValueForKeyPath:ofObject:change:context:方法檀轨,這個(gè)方法當(dāng)觀察的屬性變化時(shí)會自動調(diào)用(這是一個(gè)回調(diào)方法)
3.取消注冊觀察removeObserver:forKeyPath:context:(在dealloc里面寫)
例子:
//定義一個(gè)Person類? 有兩個(gè)屬性name 和 age
@interface Person : NSObject
{
NSString*_name;
int????? _age;
} @end
//定義一個(gè)viewController 用來測試
#import "Person.h"
@interface ViewController :UIViewController
@property (nonatomic, retain) Person* testPerson;
@end
- (void)viewDidLoad {
[superviewDidLoad];
//創(chuàng)建Person對象
testPerson = [[myPerson alloc] init];
//第一步:添加觀察者self
[testPerson addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew ? ?context:nil];?
}
//第二步 添加回調(diào)方法 ?當(dāng)要觀察的值發(fā)生變化時(shí) 進(jìn)行自己想要的操作
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if?([keyPath?isEqualToString:@"age"])?{
NSLog(@"new Age =%@",?[change?valueForKey:NSKeyValueChangeNewKey]);
}?
}
//第三步移除觀察者
-?(void)dealloc
{
[testPerson?removeObserver:self?forKeyPath:@"age"?context:nil];
[super?dealloc];
}
感謝碼迷的文章