KVO

KVO:全名为:KeyValue Observing,直译为:基于键值的观察者。

KVO主要用于视图交互方面,比如界面的某些数据变化了,界面的显示也跟着需要变化,那就要建立数据和界面的关联

//自己的代码

//test_class.h

#import <Foundation/Foundation.h>

 @interface test_class : NSObject

 @end


//test_class.m

#import "test_class.h"

 @implementationtest_class

 //这里实现方法

-(void) observeValueForKeyPath:(NSString *)keyPath

                     ofObject:(id)object

                       change:(NSDictionary *)change

                      context:(void *)context

{

    if([keyPath isEqual:@"balance"])

    {

        NSLog(@"invoke observefun! old value is[%@],new value is[%@]",change[@"old"],change[@"new"]);

    }

}

@end

//account_class.h

#ifndefKVO_test_account_class_h

#defineKVO_test_account_class_h

#import <Foundation/Foundation.h>

@interface Account : NSObject

 #pragma mark - 属性

@property (nonatomic,assign) float balance;

 - (void) change:(float)NewBalance;

- (void) newChange:(float)value;

 @end

 #endif

//account_class.m

#import <Foundation/Foundation.h>

#import "account_class.h"

 @implementation Account

 - (void) change:(float)NewBalance

{

    _balance = NewBalance;

    NSLog(@"invoke change:fun! new value = [%f]",NewBalance);

}

 

-(void) newChange:(float)value

{

    self.balance =value;

     NSLog(@"invokenewChange: fun! new value = [%f]",value);

}

 @end


//main.m

#import <Foundation/Foundation.h>

#import "account_class.h"

#import "test_class.h"

 

int main(intargc, const char* argv[])

{

    @autoreleasepool

    {

       

       Account *account2 = [[Account alloc]init];

       

       account2.balance = 100;

       

       test_class *testObj = [[test_class alloc]init];

        //account2对象添加监视器(testObj)用来监视某个键的值是否发生变化(这里是balance属性),监视器类中要实现observeValueForKeyPath...的方法

       [account2 addObserver:testObj forKeyPath:@"balance"

                     options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld

                     context:nil];

        //通过KVC修改值,会报给监视器

       [account2 setValue:@"200" forKey:@"balance"];

        //通过存取方法修改属性值,会报给监视器

       account2.balance = 300;

        //直接对值进行修改,未调用属性方法,不会报告给监视器

       [account2 change:400];

        //使用属性方法修改值,会报给监视器,实际上会先调用监视器的方法

       [account2 newChange:600];

        //去掉特定对象对特定键路径的监视

       [account2 removeObserver:testObj forKeyPath:@"balance"];

        //此时修改值就不在报给监视器了

       [account2 setValue:@500 forKey:@"balance"];

       

        NSLog(@"last value is[%ld]",[[account2 valueForKey:@"balance"]integerValue]);

       

       

    }

    return 0;

}

  

 


 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值