KVO底层实现原理

首先:添加观察着对象的时候,干了啥事呢?系统创建了一个字类名为:NSKVONotifing_父类,并且重写了被观察者对象的监听属性的setter方法,setter方法里面又重写了

父类的setter方法,同时ISA指针指向了子类,当后面更改属性值的时候,即person.height = 181是相当于son.height = 181,由于里面重写了父类的setter方法,故先调用了willchange方法,记录old属性,然后更改了height的值,然后调用oberserveValueForKey方法,传递旧值和新值.

 


//


//  ViewController.m


//  KVO底层实现原理


//


//  Created by 曹魏 on 2018/1/8.


//  Copyright © 2018年 itcast. All rights reserved.


//


 


#import "ViewController.h"


#import "CWPerson.h"


@interface ViewController ()


@property (nonatomic,strong)CWPerson *person;


@end


@implementation ViewController 


- (void)viewDidLoad {


    [super viewDidLoad];


    CWPerson *person = [[CWPerson alloc]init];


    self.person = person;


    person.name = @"刘德华";


    person.height = 180;


    person.age = 50;


    //添加监听者对象


    [person addObserver:self forKeyPath:@"height" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil];


    person.height = 181;


    person.age = 51;


}

//实现监听者方法


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


    NSLog(@"%@",context);


}

//移除监听者对象


- (void)dealloc{


    [self.person removeObserver:self forKeyPath:@"height"];

}

@end


子类:其实是苹果自己重写的子类,下面的是我自己重写的,其实子类名应该是NSKVONotifing_CWPerson

#import "CWSon.h"

@implementation CWSon
- (void)setHeight:(CGFloat)height{
    [super setHeight:height];
    
}
@end

 

posted @ 2018-01-07 23:47  忆缘晨风  阅读(184)  评论(0编辑  收藏  举报