美文网首页
YYKit 实用分类方法中runtime方法的应用(1)

YYKit 实用分类方法中runtime方法的应用(1)

作者: YannChee | 来源:发表于2018-12-11 11:53 被阅读12次

    之前只使用了YYModel框架,YYModel 是YYKit的一部分,最近翻看了一下YYKit源码,发现开发中常见的大部分方法YYKit都做了封装,根本不用重复造轮子,YYKit值得好好研究.

    NSObject+YYAdd.h

    最常用利用runtime 进行方法交换

     + (BOOL)swizzleInstanceMethod:(SEL)originalSel with:(SEL)newSel;
     + (BOOL)swizzleClassMethod:(SEL)originalSel with:(SEL)newSel;
    
    + (BOOL)swizzleInstanceMethod:(SEL)originalSel with:(SEL)newSel {
        Method originalMethod = class_getInstanceMethod(self, originalSel);
        Method newMethod = class_getInstanceMethod(self, newSel);
        if (!originalMethod || !newMethod) return NO;
        
        class_addMethod(self,
                        originalSel,
                        class_getMethodImplementation(self, originalSel),
                        method_getTypeEncoding(originalMethod));
        class_addMethod(self,
                        newSel,
                        class_getMethodImplementation(self, newSel),
                        method_getTypeEncoding(newMethod));
        
        method_exchangeImplementations(class_getInstanceMethod(self, originalSel),
                                       class_getInstanceMethod(self, newSel));
        return YES;
    }
    
    + (BOOL)swizzleClassMethod:(SEL)originalSel with:(SEL)newSel {
        Class class = object_getClass(self);
        Method originalMethod = class_getInstanceMethod(class, originalSel);
        Method newMethod = class_getInstanceMethod(class, newSel);
        if (!originalMethod || !newMethod) return NO;
        method_exchangeImplementations(originalMethod, newMethod);
        return YES;
    }
    
    

    动态增加对象属性

    - (void)setAssociateValue:(nullable id)value withKey:(void *)key; // 给对象设置strong属性并赋值
    - (void)setAssociateWeakValue:(nullable id)value withKey:(void *)key;// 给对象设置weak属性并赋值
    - (nullable id)getAssociatedValueForKey:(void *)key;
    - (void)removeAssociatedValues;
    
    - (void)setAssociateValue:(id)value withKey:(void *)key {
        objc_setAssociatedObject(self, key, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    - (void)setAssociateWeakValue:(id)value withKey:(void *)key {
        objc_setAssociatedObject(self, key, value, OBJC_ASSOCIATION_ASSIGN);
    }
    
    - (void)removeAssociatedValues {
        objc_removeAssociatedObjects(self);
    }
    
    - (id)getAssociatedValueForKey:(void *)key {
        return objc_getAssociatedObject(self, key);
    }
    

    相关文章

      网友评论

          本文标题:YYKit 实用分类方法中runtime方法的应用(1)

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