cocoa框架中不少地方都使用了观察者模式框架
Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。每次指定的被观察的对象的属性被修改后,KVO自动通知相应的观察者。ide
model中的定义:post
@interface StockData : NSObject { NSString * stockName; float price; }@end @implementation StockData@end
controller中使用,记得上一篇怎么说的吗?这里至关于跟模型说,我要收听你的更新广播spa
- (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 = [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]; }
用户单击View中的button调用控制器中的action去更改模型中的数据code
-(void) buttonAction { [stockForKVO setValue:@"20.0" forKey:@"price"]; }
控制器须要实现的回调,至关于收到广播后我应该作啥事orm
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if([keyPath isEqualToString:@"price"]) { myLabel.text = [stockForKVO valueForKey:@"price"]; } }
视图dealloc须要取消观察server
- (void)dealloc { [super dealloc]; [stockForKVO removeObserver:self forKeyPath:@"price"]; [stockForKVO release]; }
通知使用起来很是的简单:对象
首先定义回调,即发生通知了我应该作啥事。rem
- (void)callBack{ NSLog(@"我收到通知了!"); }
其次,注册通知,即告诉通知中心,我对啥通知感兴趣get
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(callBack) name: @"A类通知" object: nil];
第三,在程序任何一个地方均可以发送通知
- (void)getNotofocation{ NSLog(@"get it."); //发出通知 [[NSNotificationCenter defaultCenter] postNotificationName:@"A类通知" object:self]; }
固然,也能够在须要的时候取消注册通知。