- iOS:KVO的概述與使用
一,概述
- KVO,即:Key-Value Observing,它提供一種機(jī)制,當(dāng)指定的對(duì)象的屬性被修改后,則對(duì)象就會(huì)接受到通知。簡(jiǎn)單的說(shuō)就是每次指定的被觀察的對(duì)象的屬性被修改后,KVO就會(huì)自動(dòng)通知相應(yīng)的觀察者了。
二,使用方法
- 系統(tǒng)框架已經(jīng)支持KVO,所以程序員在使用的時(shí)候非常簡(jiǎn)單。
- 注冊(cè),指定被觀察者的屬性,
- 實(shí)現(xiàn)回調(diào)方法
- 移除觀察
三,實(shí)例:
- 假設(shè)一個(gè)場(chǎng)景,股票的價(jià)格顯示在當(dāng)前屏幕上,當(dāng)股票價(jià)格更改的時(shí)候,實(shí)時(shí)顯示更新其價(jià)格。
- 1.定義DataModel,
@interface StockData : NSObject {
NSString * stockName;
float price;
}
@end
@implementation StockData
@end
//2.定義此model為Controller的屬性,實(shí)例化它,監(jiān)聽(tīng)它的屬性,并顯示在當(dāng)前的View里邊
- (void)viewDidLoad
{
[super viewDidLoad];
stockForKVO = [[StockData alloc] init];
[stockForKVO setValue:@"searph" forKey:@"stockName"];
[stockForKVO setValue:@"10.0" forKey:@"price"];
[stockForKVO addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
myLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 30 )];
myLabel.textColor = [UIColor redColor];
myLabel.text =[NSString stringWithFormat:@"%@",[stockForKVO valueForKey:@"price"]] ;
[self.view addSubview:myLabel];
UIButton * b = [UIButton buttonWithType:UIButtonTypeRoundedRect];
b.frame = CGRectMake(0, 0, 100, 30);
[b addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:b];
}
//3.當(dāng)點(diǎn)擊button的時(shí)候,調(diào)用buttonAction方法,修改對(duì)象的屬性
-(void) buttonAction
{
[stockForKVO setValue:@"20.0" forKey:@"price"];
}
//4. 實(shí)現(xiàn)回調(diào)方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:@"price"])
{
myLabel.text =[NSString stringWithFormat:@"%@",[stockForKVO valueForKey:@"price"]] ;
}
}
//5.增加觀察與取消觀察是成對(duì)出現(xiàn)的,所以需要在最后的時(shí)候,移除觀察者
- (void)dealloc
{
[super dealloc];
[stockForKVO removeObserver:self forKeyPath:@"price"];
[stockForKVO release];
}
四,小結(jié)
- KVO這種編碼方式使用起來(lái)很簡(jiǎn)單,很適用與datamodel修改后,引發(fā)的UIVIew的變化這種情況,就像上邊的例子那樣,當(dāng)更改屬性的值后,監(jiān)聽(tīng)對(duì)象會(huì)立即得到通知。