IOS设计模式之四:观察者模式
来源:互联网 发布:股票手机交易软件 编辑:程序博客网 时间:2024/05/17 06:48
cocoa框架中很多地方都使用了观察者模式
一、KVO
Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。每次指定的被观察的对象的属性被修改后,KVO自动通知相应的观察者。
model中的定义:
@interface StockData : NSObject { NSString * stockName; float price;}@end@implementation StockData@end
controller中使用,记得上一篇怎么说的吗?这里相当于跟模型说,我要收听你的更新广播
- (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去更改模型中的数据
-(void) buttonAction{ [stockForKVO setValue:@"20.0" forKey:@"price"];}
控制器需要实现的回调,相当于收到广播后我应该做啥事
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ if([keyPath isEqualToString:@"price"]) { myLabel.text = [stockForKVO valueForKey:@"price"]; }}
视图dealloc需要取消观察
- (void)dealloc{ [super dealloc]; [stockForKVO removeObserver:self forKeyPath:@"price"]; [stockForKVO release];}
二、Notification
通知使用起来非常的简单:
首先定义回调,即发生通知了我应该做啥事。
- (void)callBack{ NSLog(@"我收到通知了!");}
其次,注册通知,即告诉通知中心,我对啥通知感兴趣
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(callBack) name: @"A类通知" object: nil];
第三,在程序任何一个地方都可以发送通知
- (void)getNotofocation{ NSLog(@"get it."); //发出通知 [[NSNotificationCenter defaultCenter] postNotificationName:@"A类通知" object:self];}
当然,也可以在需要的时候取消注册通知。
转载:http://www.cnblogs.com/limlee/archive/2012/06/21/2547582.html
- IOS设计模式之四:观察者模式
- IOS设计模式之四:观察者模式
- IOS设计模式之四:观察者模式
- IOS设计模式之四:观察者模式
- 【转载】IOS设计模式之四:观察者模式(转)
- 设计模式之四-观察者模式
- 设计模式系列之四:观察者模式
- 设计模式之四观察者模式
- iOS设计模式之观察者模式
- iOS设计模式之观察者模式
- iOS设计模式之观察者模式
- IOS设计模式之观察者模式
- iOS设计模式之观察者模式
- iOS设计模式之观察者模式
- iOS设计模式之观察者模式
- IOS设计模式之观察者模式
- iOS设计模式之观察者模式
- iOS设计模式:观察者
- IOS设计模式之三:MVC模式
- aspxgridview CustomButtonCallback 不支持弹出消息提示
- poj 1700 过河问题
- Js中的window.parent ,window.top,window.self 详解
- 程序员的职业素养
- IOS设计模式之四:观察者模式
- 数据库分区
- Nginx源代码分析【包含引用】
- 如何查看java对象所占的内存大小
- 举例说明怎样删除android的gallery中的图片
- JS在TextArea光标位置插入文字+移动光标到文字末尾
- SVN Label: Window -> Preferences -> Team -> SVN -> Label Decoration
- Oracle数据库中分区表的操作方法
- 运营商的轮回