美文网首页
KVO的底层实现原理

KVO的底层实现原理

作者: 三十一_iOS | 来源:发表于2017-01-09 17:38 被阅读111次
    Runtime.png

    主要是写一下自己对如何自己动手实现 KVO这个文章的理解。

    当你观察一个对象时,一个新的类会动态被创建。这个类继承自该对象的原本的类,并重写了被观察属性的 setter
    方法。自然,重写的 setter
    方法会负责在调用原 setter
    方法之前和之后,通知所有观察对象值的更改。最后把这个对象的 isa
    指针 ( isa
    指针告诉 Runtime 系统这个对象的类是什么 ) 指向这个新创建的子类,对象就神奇的变成了新创建的子类的实例。
    原来,这个中间类,继承自原本的那个类。不仅如此,Apple 还重写了 -class
    方法,企图欺骗我们这个类没有变,就是原本那个类。更具体的信息,去跑一下 Mike Ash 的那篇文章里的代码就能明白,这里就不再重复

    先放上demo地址(不是我写的,还没那个功力,只是记录下我的理解)

    作者自己总结的思路

    1. 检查对象的类有没有相应的 setter 方法。如果没有抛出异常;
    • 检查对象 isa
    • 指向的类是不是一个 KVO 类。如果不是,新建一个继承原来类的子类,并把 isa
      指向这个新建的子类;
    • 检查对象的 KVO 类重写过没有这个 setter 方法。如果没有,添加重写的 setter 方法;
    • 添加这个观察者

    以下我根据作者的代码通过搜索,一步步的写出作者每一步代码的意思,生硬的写出。

    1、方法 - (void)PG_addObserver:(NSObject *)observer forKey:(NSString *)key withBlock:(PGObservingBlock)block;

    - (void)PG_addObserver:(NSObject *)observer
                    forKey:(NSString *)key
                 withBlock:(PGObservingBlock)block
    {
        //setterForGetter 通过要观察的 key 组装 set方法字符串
        //NSSelectorFromString 通过字符串 生成 SEL
        SEL setterSelector = NSSelectorFromString(setterForGetter(key));
        //class_getInstanceMethod 通过SEL 获取 [self class] 实例方法 Method
        Method setterMethod = class_getInstanceMethod([self class], setterSelector);
        //如果实例方法不存在
        if (!setterMethod) {
            NSString *reason = [NSString stringWithFormat:@"Object %@ does not have a setter for key %@", self, key];
            @throw [NSException exceptionWithName:NSInvalidArgumentException
                                           reason:reason
                                         userInfo:nil];
            
            return;
        }
        //1,取的当前类
        Class clazz = object_getClass(self);
        //2,根据类得到类名称的字符串
        NSString *clazzName = NSStringFromClass(clazz);
        
        // if not an KVO class yet
        //3,判断类名称是否包含 kPGKVOClassPrefix
        //判断KVO子类是否创建
        if (![clazzName hasPrefix:kPGKVOClassPrefix]) {
            //如果不包含,创建当前类的子类 用于KVO
            clazz = [self makeKvoClassWithOriginalClassName:clazzName];
            
            //将self isa 指向 clazz
            
            //这可以用在Key Value Observing。当你开始observing an object时,Cocoa会创建这个object的class的subclass,然后将这个object的isa指向新创建的subclass。
            //  http://blog.jobbole.com/45963/
            
            //简单粗暴的理解就是 建立一个子类,替代现有父类
            //把当前类实例self,指向子类clazz
            
             /**
             * Sets the class of an object.
             *
             * @param obj The object to modify.
             * @param cls A class object.
             *
             * @return The previous value of \e object's class, or \c Nil if \e object is \c nil.
             */
            
            object_setClass(self, clazz);
        }
        
        // add our kvo setter if this class (not superclasses) doesn't implement the setter?
        
        //判断是否已经创建 新的set 方法
        if (![self hasSelector:setterSelector]) {
            const char *types = method_getTypeEncoding(setterMethod);
            //创建新的set方法 替换原有的方法
            
            //class_addMethod的4个参数分别添加方法的目标类、新方法的选择器、函数的地址(数据类型为IMP)和描述方法参数的数据类型的字符串(字符串里的内容分别依次为函数返回值类型和每个参数类型,在这里v表示void,@表示selector,:表示IMP)
            //http://blog.csdn.net/lvmaker/article/details/32396167
            
            // setterSelector 方法名
            //(IMP)kvo_setter setterSelector 的具体实现!!!!!!
            class_addMethod(clazz, setterSelector, (IMP)kvo_setter, types);
        }
        
        PGObservationInfo *info = [[PGObservationInfo alloc] initWithObserver:observer Key:key block:block];
        
        //关联对象
        //objc_getAssociatedObject 相当于get方法读取
        NSMutableArray *observers = objc_getAssociatedObject(self, (__bridge const void *)(kPGKVOAssociatedObservers));
        if (!observers) {
            //如果没有 objc_setAssociatedObject 相当于调用set方法
            observers = [NSMutableArray array];
            objc_setAssociatedObject(self, (__bridge const void *)(kPGKVOAssociatedObservers), observers, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        }
        //加入数组
        [observers addObject:info];
    }
    
    

    2、方法 static NSString * setterForGetter(NSString *getter) 根据key组装set方法的字符串

    
    static NSString * setterForGetter(NSString *getter)
    {
        if (getter.length <= 0) {
            return nil;
        }
        // upper case the first letter
        //取出首字母 并且大写
        NSString *firstLetter = [[getter substringToIndex:1] uppercaseString];
        //取出余下字符串
        NSString *remainingLetters = [getter substringFromIndex:1];
        // add 'set' at the begining and ':' at the end
        // eg:把 method 修改为 setMethod:
        NSString *setter = [NSString stringWithFormat:@"set%@%@:", firstLetter, remainingLetters];
        return setter;
    }
    

    3、方法 - (Class)makeKvoClassWithOriginalClassName:(NSString *)originalClazzName 为当前类创建子类,用于观察值的变化

    - (Class)makeKvoClassWithOriginalClassName:(NSString *)originalClazzName
    {
        //拼接 kPGKVOClassPrefix 作为子类名称
        NSString *kvoClazzName = [kPGKVOClassPrefix stringByAppendingString:originalClazzName];
        //由 字符串 得到类
        Class clazz = NSClassFromString(kvoClazzName);
        //如果clazz类存在 直接返回 clazz
        if (clazz) {
            return clazz;
        }
        
        //如果clazz 不存在  创建 注册
        //为了创建一个新类,我们需要调用objc_allocateClassPair。然后使用诸如class_addMethod,class_addIvar等函数来为新创建的类添加方法、实例变量和属性等。完成这些后,我们需要调用objc_registerClassPair函数来注册类,之后这个新类就可以在程序中使用了。
    
        // class doesn't exist yet, make it
        //取得当前类
        Class originalClazz = object_getClass(self);
        //创建 kvoClazzName 类 并且把originalClazz 当做父类
        Class kvoClazz = objc_allocateClassPair(originalClazz, kvoClazzName.UTF8String, 0);
        // grab class method's signature so we can borrow it
        //获取实例方法 class
        Method clazzMethod = class_getInstanceMethod(originalClazz, @selector(class));
        const char *types = method_getTypeEncoding(clazzMethod);
        // class_addMethod的4个参数分别添加方法的目标类、新方法的选择器、函数的地址(数据类型为IMP)和描述方法参数的数据类型的字符串(字符串里的内容分别依次为函数返回值类型和每个参数类型,在这里v表示void,@表示selector,:表示IMP)
        //下面代码的意思 就是为kvoClazz添加一个class方法,具体的实现是(IMP)kvo_class
        class_addMethod(kvoClazz, @selector(class), (IMP)kvo_class, types);
        objc_registerClassPair(kvoClazz);
        return kvoClazz;
    }
    

    4,方法 - (BOOL)hasSelector:(SEL)selector 判断 selector 是否已经存在

    - (BOOL)hasSelector:(SEL)selector
    {
        Class clazz = object_getClass(self);
        unsigned int methodCount = 0;
        //class_copyMethodList 取得clazz方法列表
        Method* methodList = class_copyMethodList(clazz, &methodCount);
        //判断selector 是否已经存在
        for (unsigned int i = 0; i < methodCount; i++) {
            SEL thisSelector = method_getName(methodList[i]);
            if (thisSelector == selector) {
                free(methodList);
                return YES;
            }
        }
        
        free(methodList);
        return NO;
    }
    

    5、 runtime 函数

    1. class_getInstanceMethod
    /** 
     * Returns a specified instance method for a given class.
     * 
     * @param cls The class you want to inspect.
     * @param name The selector of the method you want to retrieve.
     * 
     * @return The method that corresponds to the implementation of the selector specified by 
     *  \e name for the class specified by \e cls, or \c NULL if the specified class or its 
     *  superclasses do not contain an instance method with the specified selector.
     *
     * @note This function searches superclasses for implementations, whereas \c class_copyMethodList does not.
     */
        Method setterMethod = class_getInstanceMethod([self class], setterSelector);
    
    

    我的理解是:根据SEL 取得Class的具体实现方法

    2. class_getInstanceMethod
            /**
             * Sets the class of an object.
             *
             * @param obj The object to modify.
             * @param cls A class object.
             *
             * @return The previous value of \e object's class, or \c Nil if \e object is \c nil.
             */
    
    
        设置对象的类
        object_setClass(self, clazz);
    

    我的理解就是为实例self 设置类为 clazz

    3. class_addMethod
    /** 
     * Adds a new method to a class with a given name and implementation.
     * 
     * @param cls The class to which to add a method.
     * @param name A selector that specifies the name of the method being added.
     * @param imp A function which is the implementation of the new method. The function must take at least two arguments—self and _cmd.
     * @param types An array of characters that describe the types of the arguments to the method. 
     * 
     * @return YES if the method was added successfully, otherwise NO 
     *  (for example, the class already contains a method implementation with that name).
     *
     * @note class_addMethod will add an override of a superclass's implementation, 
     *  but will not replace an existing implementation in this class. 
     *  To change an existing implementation, use method_setImplementation.
     */
    
    
    
            class_addMethod(clazz, setterSelector, (IMP)kvo_setter, types);
    

    我的理解,其实就是翻译下英文 囧RZ。
    为类添加一个方法,clazz : 那个类需要添加方法
    setterSelector : 添加方法的SEL
    kvo_setter:(implementation 实现)具体实现
    types:参数数组

    4. objc_getAssociatedObject objc_setAssociatedObject

    相当于getter、setter

    5. object_getClass
    Class clazz = object_getClass(self);
    

    根据实例self得到self的类。

    6. objc_allocateClassPair
    /** 
     * Creates a new class and metaclass.
     * 
     * @param superclass The class to use as the new class's superclass, or \c Nil to create a new root class.
     * @param name The string to use as the new class's name. The string will be copied.
     * @param extraBytes The number of bytes to allocate for indexed ivars at the end of 
     *  the class and metaclass objects. This should usually be \c 0.
     * 
     * @return The new class, or Nil if the class could not be created (for example, the desired name is already in use).
     * 
     * @note You can get a pointer to the new metaclass by calling \c object_getClass(newClass).
     * @note To create a new class, start by calling \c objc_allocateClassPair. 
     *  Then set the class's attributes with functions like \c class_addMethod and \c class_addIvar.
     *  When you are done building the class, call \c objc_registerClassPair. The new class is now ready for use.
     * @note Instance methods and instance variables should be added to the class itself. 
     *  Class methods should be added to the metaclass.
     */
    Class kvoClazz = objc_allocateClassPair(originalClazz, kvoClazzName.UTF8String, 0);
    

    创建一个新类名称为kvoClazzName,父类为originalClazz,分配内存大小为0

    7. objc_registerClassPair
        objc_registerClassPair(kvoClazz);
    

    注册 kvoClazz

    相关文章

      网友评论

          本文标题:KVO的底层实现原理

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