OC KVO学习

KVO

      KVO 即 Key-Value Observing键值监听。可以将其直接理解为观察者模式。

      例如,存在一个Person类和一个Account类分别代表一个人和一个银行账户,每当银行账户发生变化时,Person应当收到一个更改通知,知道自己账户变化。

//
//  ViewController.m
//  MyFirstApp
//
//  Created by yongxu duan on 2021/7/6.
//

#import "ViewController.h"
#import <Foundation/NSKeyValueCoding.h>

#import "Person.h"
#import <objc/runtime.h>

@interface Account : NSObject
@property int num;
@end
@implementation Person
@end

@implementation Account

@end

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self test];
}
static void *PersonAccountBalanceContext = &PersonAccountBalanceContext;

- (void)test{
    Person *per = [Person new];
    per.name = @"LiMing";
    
    Account *acc = [Account new];
    acc.num = 2;
    
    Class clazz = object_getClass(acc);//获取类
    Class supClazz = class_getSuperclass(clazz);//获取父类
    
    NSLog(@"添加KVO之前的类:%@, 父类:%@ ",clazz,supClazz);
    //设置观察者
    [acc addObserver:self forKeyPath:@"num" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:PersonAccountBalanceContext];
    
    clazz = object_getClass(acc);
    supClazz = class_getSuperclass(clazz);
    
    NSLog(@"添加KVO之前的类:%@, 父类:%@ ",clazz,supClazz);
    per.name = @"LISI";//更改属性后应该有得到通知
    acc.num = 12;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if(context == PersonAccountBalanceContext){
        NSLog(@"same");
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
@end

运行结果如下:

在这里插入图片描述
如上图所示,在创建了观察者之后,OC创建了一个NSKVONotifying_Account的类继承Account类。同时更改记录在change中打印出。

未完待续

猜你喜欢

转载自blog.csdn.net/Ambrosedream/article/details/118547734
今日推荐