ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
_p = [Person new];
[_p WW_addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:NULL];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
NSLog(@"%@",change);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
int i = arc4random() % 100;
_p.name = [NSString stringWithFormat:@"%d",i];
}
创建一个Person类,添加一个name属性
NSObject+KVO
- (void)WW_addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context{
//获取类名
NSString *oldName = NSStringFromClass([self class]);
//创建子类类名
NSString *newName = [@"WWKVO_" stringByAppendingString:oldName];
//动态创建类
Class newClass = objc_allocateClassPair([self class], newName.UTF8String, 0);
/**
可根据keyPath动态设置SEL名称
*/
//动态创建方法
class_addMethod(newClass, @selector(setName:), (IMP)setName1, "v@:@");
//注册类
objc_registerClassPair(newClass);
//修改isa指针
object_setClass(self, newClass);
/**
可根据keyPath动态设置key
*/
//绑定属性
objc_setAssociatedObject(self, (__bridge const void*)@"observe", observer, OBJC_ASSOCIATION_RETAIN);
}
//重写父类方法
void setName1(id self,SEL _cmd ,NSString *newVlaue){
/**
可根据SEL动态获取属性名称
*/
//保存当前类
Class class = [self class];
//修改isa指针,调用父类方法
object_setClass(self, class_getSuperclass([self class]));
//获取旧值
objc_property_t pro = class_getProperty([self class], "name");
const char *name = property_getName(pro);
NSString *oldPro = [NSString stringWithUTF8String:name];
id oldName = [self valueForKey:oldPro];
//调用父类方法
((void(*)(id,SEL,NSString*))objc_msgSend)(self,@selector(setName:),newVlaue);
//获取observe
id observe = objc_getAssociatedObject(self, (__bridge const void*)@"observe");
//返回值
NSDictionary *dict = oldName? @{NSKeyValueChangeOldKey:oldName,NSKeyValueChangeNewKey:newVlaue}:@{NSKeyValueChangeNewKey:newVlaue};
//发送消息
((void(*)(id,SEL,NSString *,id,id,id))objc_msgSend)(observe,@selector(observeValueForKeyPath:ofObject:change:context:),@"name",self,dict,nil);
//交换
object_setClass(self, class);
}