ios观察者模式之kvo
首先得先了解KVC,KVC (Key Value Coding),简单来讲,就是给属性设置值的;
KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。
KVO是基于KVC实现的。(常用在股票等需要实时监控得场景)
demo下载:https://github.com/MartinLi841538513/KVO_Demo
核心代码(代码中用到定时器是为了更好得展示效果):
// // Book.m // KVO // // Created by dongway on 14-8-4. // Copyright (c) 2014年 dongway. All rights reserved. // #import "Book.h" @implementation Book -(id)init{ if (self = [super init]) { count = 0; } return self; } -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ if ([keyPath isEqualToString:@"price"]) { NSLog(@"old:%@",[change valueForKey:@"old"]); NSLog(@"new:%@",[change valueForKey:@"new"]); }else if([keyPath isEqualToString:@"name"]){ NSLog(@"new name:%@",[change valueForKey:@"new"]); } } -(void)addObserver{ [self addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil]; [self addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil]; timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changePrice) userInfo:nil repeats:YES]; } -(void)changePrice{ count++; if (count<10) { //只要value的值一改变,就会触发监听方法。达到实时监听的作用 [self setValue:[NSString stringWithFormat:@"%d",count] forKey:@"price"]; [self setValue:@"ios bookname" forKey:@"name"]; NSLog(@"%@",name); }else{ [timer invalidate]; } } @end