• KVO


    Dog类.h:

    @interface Dog : NSObject{

        NSString *dogName;

    }

    Person类.h:

    #import "Dog.h"

    @interface Person : NSObject{

        NSString *name;

        int age;

        Dog *dg;

    }

    Person *xiaowang = [[Person alloc]init];

            //使用KVC设置变量的值

            //使用之前必须知道变量的名字

            [xiaowang setValue:@"小王" forKey:@"name"];

            NSString *name = [xiaowang valueForKey:@"name"];

            NSLog(@"%@",name);

            

            //对类里面的某个对象变量的实行设置

            Dog *ww = [[Dog alloc]init];

            [xiaowang setValue:ww forKey:@"dg"];

            

            [xiaowang setValue:@"汪汪" forKeyPath:@"dg.dogName"];

            NSString *dgName = [xiaowang valueForKeyPath:@"dg.dogName"];

            NSLog(@"%@",dgName);

     KVO2:

    CreatedCard类.h:

    @interface CreatedCard : NSObject{

        int money;

    }

    Person类.h:

    @property (nonatomic,strong)CreatedCard *card;

    Person类.m:

    -(void)dealloc{

        [_card release];

        [self removeObserver:self forKeyPath:@"card.money"];

        [super dealloc];

    }

    -(instancetype)init{

        if (self = [super init]) {

            self.card = [[[CreatedCard alloc]init]autorelease] ;

            //当前这个类添加一个监听器,监听card对象的money属性,监听这个属性变化之前之后的值

            [self addObserver:self forKeyPath:@"card.money" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];

        }

        return self;

    }

    //属性变化之后的回调

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

        int oldValue = [[change objectForKey:NSKeyValueChangeOldKey]intValue];

        int newValue = [[change objectForKey:NSKeyValueChangeNewKey]intValue];

        NSLog(@"old:%d",oldValue);

        NSLog(@"new:%d",newValue);

    }

     main:

    #import <Foundation/Foundation.h>

    #import "Person.h"

    int main(int argc, const char * argv[]) {

        @autoreleasepool {

            Person *xw = [[[Person alloc]init]autorelease];

            [xw setValue:@1000 forKeyPath:@"card.money"];

            [xw setValue:@2000 forKeyPath:@"card.money"];

        }

        return 0;

    }

  • 相关阅读:
    ExtJs控件属性配置详细
    static void和void区别(转)
    OpenSSL 内存管理分析笔记
    Openssl 之大数运算函数 BN
    python学习:字符串
    python学习:字典
    python学习:购物车程序
    python学习:元组和嵌套
    python学习:列表
    python学习:continue及break使用
  • 原文地址:https://www.cnblogs.com/yangqinglong/p/5363204.html
Copyright © 2020-2023  润新知