添加觀察者方法實現(xiàn)原理
#import "NSObject+KVO.h"
#import "XMKVONotifying_Person.h"
#import <objc/runtime.h>
@implementation NSObject (KVO)
-(void)XM_addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options: (NSKeyValueObservingOptions)options context:(void *)context
{
//1.動態(tài)創(chuàng)建NSKVONotifying_Person,NSKVONotifying_Person是Person子類,做KVO
//2.修改當前對象的isa指針->NSKVONotifying_Person
//3.只要調(diào)用對象的set,就會調(diào)用NSKVONotifying_Person的set方法
//4.重寫NSKVONotifying_Person的set方法,1.[super set:] 2.通知觀察者,告訴你屬性改變
//修改isa,本質(zhì)就是改變當前對象的類名
object_setClass(self, [XMKVONotifying_Person class]);
把觀察者保存到當前對象里
// 添加關(guān)聯(lián)
// id object:給哪個對象添加關(guān)聯(lián)屬性
// key:屬性名
// value:關(guān)聯(lián)值
objc_setAssociatedObject(self, @"key", observer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#import "XMKVONotifying_Person.h"
#import <objc/runtime.h>
@implementation XMKVONotifying_Person
監(jiān)聽方法自動調(diào)用實現(xiàn)原理
-(void)setAge:(NSInteger)age
{
[super setAge:age];
// 通知觀察者,屬性改變
id observer = objc_getAssociatedObject(self, @"key");
[observer observeValueForKeyPath:@"age" ofObject:self change:nil context:nil];
}