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]; }
固然,也能夠在須要的時候取消註冊通知。