美文网首页
Runtime(三)动态添加一个类,KVO的底层实现原理

Runtime(三)动态添加一个类,KVO的底层实现原理

作者: 炒河粉儿 | 来源:发表于2019-08-16 10:24 被阅读0次

    动态创建一个类

    //创建一个类
    Class clazz = objc_allocateClassPair([NSObject class], "GoodPerson", 0);
    
    //添加Ivar
    class_addIvar(clazz, "_name", sizeof(NSString *), log2(sizeof(NSString *)), @encode(NSString *));
    
    class_addIvar(clazz, "_age", sizeof(NSUInteger), log2(sizeof(NSUInteger)), @encode(NSUInteger));
    
    //注册该类
    objc_registerClassPair(clazz);
    
    //创建实例对象
    id object = [[clazz alloc] init];
    
    //给Ivar赋值
    [object setValue:@"Tracy" forKey:@"name"];
    
    Ivar ageIvar = class_getInstanceVariable(clazz, "_age");
    object_setIvar(object, ageIvar, @18);
    
    //打印对象的属性值
    NSLog(@"name = %@, age = %@", [object valueForKey:@"name"], object_getIvar(object, ageIvar));
    
    //销毁类
    object = nil;
    objc_disposeClassPair(clazz);
    

    KVO的底层探究

    Person *p = [Person new];
    
    [p addObserver:self forKeyPath:@"name" options:(NSKeyValueObservingOptionNew) context:nil];
    
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
    {
        NSLog(@"改变了%@",change);
    }
    
    - (void)dealloc
    {
        [self removeObserver:self forKeyPath:@"name"];
    }
    

    通过打断点可以发现其实系统动态生成了一个NSKVONotifying_Person类,然后重写了NSKVONotifying_Person的set方法,当有新值的时候,会发送通知,调用- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context,将变化的值传递回来,从而实现KVO监听属性。

    利用下面方法,将Person作为参数传入,可以货渠道Person类和他的子类的数组,可以发现(Person, "NSKVONotifying_Person")。

    //获取指定类的子类
    + (NSArray *)findSubClass:(Class)defaultClass
    {
        //注册类的总数
        int count = objc_getClassList(NULL, 0);
        
        //创建一个数组,其中包含给定对象
        NSMutableArray *array = [NSMutableArray arrayWithObject:defaultClass];
        
        //获取所有已注册的类
        Class *classes = (Class *)malloc(sizeof(Class)*count);
        objc_getClassList(classes, count);
        
        //遍历
        for (int i = 0 ; i<count; i++) {
            if (defaultClass == class_getSuperclass(classes[i])) {
                [array addObject:classes[i]];
            }
        }
        
        free(classes);
        
        return array;
    }
    
    

    给NSObject创建一个分类,添加一个自己的方法,模拟实现KVO的监听机制。创建一个新的类,作为self的属性,重写这个类的set方法,关联这个类的属性,当有新值赋值的时候,通过objc_msgSend调用- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context进行通知。

    #import <Foundation/Foundation.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface NSObject (KVO)
    
    - (void)lwn_addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context;
    
    @end
    
    NS_ASSUME_NONNULL_END
    
    #import "NSObject+KVO.h"
    #import <objc/runtime.h>
    #import <objc/message.h>
    
    @implementation NSObject (KVO)
    
    - (void)lwn_addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context
    {
        //1.动态注册一个新的类,这个类是继承当前类的类
        NSString *oldName =  NSStringFromClass([self class]);
        NSString *newName = [NSString stringWithFormat:@"lwnKVO%@",oldName];
        Class customClass = objc_allocateClassPair([self class], newName.UTF8String, 0);
        objc_registerClassPair(customClass);
        
        //2.修改self属性
        object_setClass(self, customClass);
        
        
        //3.重写子类的set方法
        NSString *methodName = [NSString stringWithFormat:@"set%@:",keyPath.capitalizedString];
        SEL sel = NSSelectorFromString(methodName);
        class_addMethod(customClass, sel, (IMP)setName, "v@:@");
        
        
        //关联属性
        objc_setAssociatedObject(self, (__bridge const void *)@"objc", observer,OBJC_ASSOCIATION_ASSIGN);
    }
    
    void setName(id self, SEL _cmd, NSString *name) {
        NSLog(@"%@",name);
        
        struct objc_super superClass = {self,class_getSuperclass([self class])};
        
        objc_msgSendSuper(&superClass, _cmd,name);
    
        id observer = objc_getAssociatedObject(self, (__bridge const void *)@"objc");
        NSString *methodName = NSStringFromSelector(_cmd);
        NSString *key = @"name";
        
        objc_msgSend(observer, @selector(observeValueForKeyPath: ofObject: change: context:),key,self,@{key:name},nil);
    }
    

    相关文章

      网友评论

          本文标题:Runtime(三)动态添加一个类,KVO的底层实现原理

          本文链接:https://www.haomeiwen.com/subject/xvxfsctx.html