关于iphone开发中观察者模式中的kvo机制的总结

来源:互联网 发布:四川大学软件学院 编辑:程序博客网 时间:2024/06/04 20:40

在iOS中,KVO不像通知机制那样通过⼀一个通知中⼼心通知所有观察者对象,而是在对象属性变化时通知会被直接发送给观察者对象,使⽤用NSKeyValueObserving 类(NSObject的分类)。

属性发⽣生变化的对象需要发出如下消息给注册观察者,使观察者关注它的某个属性
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options: (NSKeyValueObservingOptions)options context:(void *)context

当对象属性变化时,观察者就会接收到通知,观察者需要重写此⽅方法以响应
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change: (NSDictionary *)change context:(void *)context;

在这个代码中,我是想让secondviewcontroller的textfield的内容传递到mainviewcontroller的label中。

首先我在second里面这样添加观察者

- (void)viewDidLoad{    [super viewDidLoad];    self.textt=@"";    self.main=(mainViewController*)self.presentingViewController;//返回向他present的那个视图(需要注意的地方1)    [self addObserver:self.main forKeyPath:@"textt" options:NSKeyValueObservingOptionNew context:NULL];//添加观察者}
在第一个main中,这样实现

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{    NSLog(@"keypath=%@,object=%@,change=%@",keyPath,object,change);    NSLog(@"%@",[change objectForKey:@"new"]);    self.mylabel.text=[NSString stringWithFormat:@"%@",[change objectForKey:@"new"]];    NSLog(@"%p",self);}

在second中,button的响应事件

- (IBAction)backf:(id)sender {    self.textt=self.mytext.text;//(跳转的地方)    [self dismissViewControllerAnimated:YES completion:nil];<pre name="code" class="objc">//(需要注意的地方2)
[self removeObserver:self.main forKeyPath:@"textt"]; //[self presentViewController:self.main animated:YES completion:nil];}


在main中的button的响应事件

- (IBAction)go:(id)sender {    secondViewController *second=[[secondViewController alloc]init];    [self presentViewController:second animated:YES completion:nil];}

这样以后重点就来了,第一次,在1中,如果写的是

 self.main=(mainViewController*)self.presentingViewController

那么这样就是传过来和传走都是同一个main的controller,这样才可以实现


注意:

self.main=[mainViewController alloc]init;

如果是直接alloc的话,那么他在button的响应事件中,返回的controller和传过来的不会一个,所以会传值失败

并且如果加上断点的话,在跳转的地方那里,只要值变化,他就会直接先跳转到main里面,此时的这个main函数是你新开辟的那个main,然后执行完毕之后才会继续在返回来执行dissmiss函数,执行完毕dissmiss函数之后,出现的那个main是self.presentingViewController,而不是现在这个alloc的main,所以再次出现的这个main里面是空白的,如果想实现,就不能使用dissmiss,而应该使用present传过去视图,这样的话才可以保证两个是同一个视图,才会传值成功

就是把这句

[self dismissViewControllerAnimated:YES completion:nil];
修改为:
[self presentViewController:self.main animated:YES completion:nil];



0 0
原创粉丝点击