ios kvo原理:

1. 创建CZPerson类: 

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface CZPerson : NSObject
@property (nonatomic,copy)NSString *name;
@property (nonatomic, assign)NSInteger age;
@property (nonatomic ,assign)CGFloat height;

@end

2. ViewController中: 

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    //KVO
    // key value observed
    // 监听对象属性的改变
    CZPerson *person = [[CZPerson alloc]init];
    self.person = person;
    person.name = @"明月心";
    
    person.age = 18;
    
    person.height = 1.8;
    
    //KeyPath   键值路径 
    [person addObserver:self forKeyPath:@"height" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew  context:nil];
    
    //1.保存所有参数 监听者 枚举 携带参数 路劲
    //2.创建之类NSKVONotifying_CZPerson 重写set方法
    //3.set方法 监听者 底层调用自己的方法observeValueForKeyPath
    
    
    
    //KVO的底层实现原理是啥
    //运行时 runtim
    //person.age = 19;
    //isa	Class	NSKVONotifying_CZPerson	0x00007face0d1a190
    person.height  = 1.6;  //能够执行子类NSKVONotifying_CZPerson的set方法
    
    // 监听者 底层调用自己的方法observeValueForKeyPath
    // 在什么地方调用
    // KVO 底层实现: 运行时  创建一个子类对象并且重写子类的set方法  在set方法 调用监听者的observeValueForKeyPath
    
    
    NSLog(@"%@ %zd %f",person.name,person.age,person.height);
}

- (void)dealloc
{
    [self.person removeObserver:self forKeyPath:@"height"];
}
   // 单属性改变的时候会调用这个方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    NSLog(@"%@",change);
}




猜你喜欢

转载自blog.csdn.net/dreams_deng/article/details/80776973