iOS-runtime自定义KVO----分类添加关键属性
2019-06-25 本文已影响0人
武一顶顶
1. KVO原理
2. runtime自定义KVO
3. runtime给分类添加关联属性
- 我们注册监听的时候,会对注册者动态的创建一个子类对象,然后底层找方法的的isa指针就变成指向新创建的子类对象。当改变注册对象某个属性的时候,就重写属性的set方法来进行监听。这么说可能理解上不是很明白,下面我们结合代码来分析:
- 自定义
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSObject (KVO)
@property (nonatomic, strong) NSObject *test;
@property (nonatomic, strong) NSTimer *timer;
- (void)kvo_addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context;
@end
NS_ASSUME_NONNULL_END
/***********************************************/
#import "NSObject+KVO.h"
#import <objc/message.h>
// timer 与 test 是runtime添加关联属性代码, 与自定义kvo无关
static const char *key_test = "test";
static const char *key_observer = "objc";
static const char *key_timer = "timer";
@implementation NSObject (KVO)
- (void)kvo_addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context {
NSString *oldClassName = NSStringFromClass([self class]);
NSString *newClassName = [NSString stringWithFormat:@"KVC_%@", oldClassName];
const char *newName = [newClassName UTF8String];
Class newClass = objc_allocateClassPair([self class], newName, 0);
class_addMethod(newClass,@selector(setAge:), (IMP)setAge, "v@:i");
objc_registerClassPair(newClass);
// (__bridge const void *)@"objc"
object_setClass(self, newClass);
objc_setAssociatedObject(self, key_observer, observer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
Class nclass = NSClassFromString(@"KVO_ViewController");
}
- (NSObject *)test {
NSLog(@"分类添加属性值test_get:%@",objc_getAssociatedObject(self, key_test));
return objc_getAssociatedObject(self, key_test);
}
- (void)setTest:(NSObject *)test {
NSLog(@"分类添加属性值test_set前:%@",objc_getAssociatedObject(self, key_test));
objc_setAssociatedObject(self, key_test, test, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
NSLog(@"分类添加属性值test_set后:%@",objc_getAssociatedObject(self, key_test));
}
- (void)setTimer:(NSTimer *)timer {
objc_setAssociatedObject(self, key_timer, timer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSTimer *)timer {
return objc_getAssociatedObject(self, key_timer);
}
void setAge(id self, SEL _cmd, int age) {
//保存当前类
Class myclass = [self class];
//将self的isa指针指向父类
object_setClass(self, class_getSuperclass([self class]));
//调用父类
objc_msgSend(self,@selector(setAge:),age);
//拿出观察者 (__bridge const void *)@"objc"
id objc = objc_getAssociatedObject(self, key_observer);
//通知观察者
objc_msgSend(objc,@selector(observeValueForKeyPath:ofObject:change:context:),@"age",self,@{},nil);
//改为子类
object_setClass(self, myclass);
}
@end
- 使用
#import "ViewController.h"
#import "NSObject+KVO.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// [self addObserver:(nonnull NSObject *) forKeyPath:(nonnull NSString *) options:(NSKeyValueObservingOptions) context:(nullable void *)];
self.view.backgroundColor = [UIColor whiteColor];
[self kvo_addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
self.age = 20;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
NSLog(@"自定义kvo监听到属性改变");
}
- (void)setAge:(int)age {
_age = age;
NSLog(@"方法没有被覆盖:%s", __func__);
}
@end
- 详解
1. 动态添加一个当前类的子类
NSString *oldClassName = NSStringFromClass([self class]);
NSString *newClassName = [@"AWKVO_" stringByAppendingString:oldClassName];
const char * newName = [newClassName UTF8String];
Class myclass = objc_allocateClassPair([self class], newName, 0);
//添加setter方法,相当于重写setter方法, "v@:i" 含义 @: id : SEL v : void
OC(消息发送机制),方法由两部分组成,方法编号@selector和方法实现(imp方法指针),先找方法编号再得到方法的指针,再执行方法的代码块。
class_addMethod(myclass, @selector(setAge:), (IMP)setAge, "v@:i");
//注册新添加的这个类
objc_registerClassPair(myclass);
//修改被观察这的isa指针,isa指针指向Person类改成指向myclass这个类
object_setClass(self, myclass);
//将观察者的属性保存到当前类里面去
objc_setAssociatedObject(self, (__bridge const void *)@"objc", observer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
//相当于重写父类的方法
void setAge(id self, SEL _cmd, int age) {
//保存当前类
Class myclass = [self class];
//将self的isa指针指向父类
object_setClass(self, class_getSuperclass([self class]));
//调用父类
objc_msgSend(self, @selector(setAge:),age);
//拿出观察者
objc_getAssociatedObject(self, (__bridge const void *)@"objc");
//通知观察者
objc_msgSend(objc,@selector(observeValueForKeyPath:ofObject:change:context:),self,age,nil,nil);
//改为子类
object_setClass(self, myclass);
}
这样就可以回调到ViewContoller中的监听方法observeValueForKeyPath:ofObject:change:context:中去,而且相关的值也传递过去了。
总结自定义一个KVO思路:
1.自定义一个类,继承 [self class]的一个子类
2.重写父类的属性setter方法
3.调用observeValueForKeyPath:ofObject:change:context:方法,回调到ViewController中去。
- 附加:
- 苹果为什么要用子类(就是C语言创建的那个子类)监听setter方法,而不用分类(Person+AWKVO)呢?
- 回答:原因是当你用分类监听setter方法的时候,Person类中setter方法就不会走了,这样不好,所以苹果使用了子类监听setter方法。