cocoa框架中很多地方都使用了观察者模式
一、 KVO
Key-Value Observing, 它提供一种机制,当指定的对象的属性被修改后,则观察者就会接收到通知。每次指定的被观察的对象的属性被修改后,KVO自动通知相应的观察者。
model中的定义:
@interface StockData:NSObject {
NSString *stockName;
float price;
}
@end
@implementation StockData
@end
- (void)viewDidLoad
{
[superviewDidLoad];
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 = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];
b.frame = CGRectMake(0,0, 100, 30);
[b addTarget:selfaction:@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
{
[superdealloc];
[stockForKVO removeObserver:self forKeyPath:@"price"];
[stockForKVO release];
}
二、NSNotification
通知使用起来非常的简单:
1、在程序任何一个地方都可以发送通知:
- (void)getNotofocation{
NSLog(@"get it.");
//发出通知
[[NSNotificationCenterdefaultCenter] postNotificationName:@"A类通知"object:self];
}
2、注册通知,即告诉通知中心,我对啥通知感兴趣:
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(callBack)
name: @"A类通知"
object: nil];
3、实现回调,接收到通知后,准备做啥:- (void)callBack{
NSLog(@"我收到通知了!");
}
当然,也可以在需要的时候取消注册通知。
今天在用的时候有个发现,如果在两个控制器里面收听同一个通知,然后回调方法名一模一样。那么有可能其中一个回调方法不会执行,应该命名成不同的回调方法名。
以上如有错误,希望指出~~ 共同学习,共同进步~~
2319

被折叠的 条评论
为什么被折叠?



