KVO和通知机制

来源:互联网 发布:linux squid 地址 编辑:程序博客网 时间:2024/05/18 03:45

KVO

 全称: Key Value Observing 键值监听

   当指定对象的属性被修改后。则该对象就会收到通知,也就是每次指定的被观察的对象的属性,被修改之后,kvo就会自动的通      知响应的观察者

 //第一步:注册

    /**

     *  1.注册被监听对象,也就是model

        2.addObserver  监听对象

        3.forKeyPath 被监听对象的属性

        4.options 什么时候出发,NSKeyValueObservingOptionNew当值有新变化的时候回调监听方法

 //self.model 是继承NSObject的model对象

[self.modeladdObserver:selfforKeyPath:@"money"options:NSKeyValueObservingOptionNewcontext:nil];


/**

 * 第二步:实现监听回调方法

 *

 *

 */




- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{

    

    

    

    NSLog(@"keyPath=%@,object=%@,change%@,context=%@",keyPath,object,change,context);

    

//     self.moneylabel.text=[self.model valueForKey:@"money"];

    

    

    if ([keyPathisEqualToString:@"money"]) {

        self.moneylabel.text=change[@"new"];

    }

    

    

    

    

}

/**

 *  第三步L:移除

 */

- (void)dealloc{

    

    //ARC不能写 [super dealloc];

   

    [self.modelremoveObserver:selfforKeyPath:@"money"];

    

}


//第四步:触发(改变model属性的值)

- (IBAction)lookBtn:(id)sender {

    NSString *str=[NSStringstringWithFormat:@"余额:%ldRMB",arc4random() % 10000000000];

    [self.modelsetValue:strforKey:@"money"];

    

    

}


#pragma mark ===== 通知


 //1.注册通知

   //通知是一对多的关系,发送一个通知,可以有多个观察者【,

    

   //,,(一定要先注册,在发送通知)

   //1.添加观察者(接受者一定要存在)

   //2.收到通知之后要执行的方法

    //3.通知的名字

    //4.传递参数为nil

    //

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(changeLabel:)name:@"zhang"object:nil];


移除通知

- (void)dealloc{

    [[NSNotificationCenterdefaultCenter]removeObserver:self];


}

收到通知的方法

-(void)changeLabel:(NSNotification *)notification{

    

    self.mango.text=notification.userInfo[@"input"];

    

}


- (IBAction)btn:(id)sender {

    //2发送通知

    [[NSNotificationCenterdefaultCenter]postNotificationName:@"zhang"object:niluserInfo:@{@"input":self.textfiled.text}];

    

    [self.navigationControllerpopToRootViewControllerAnimated:YES];

    

    

}




0 0
原创粉丝点击