关于runtime的一些方法

作者: Mr_Zeng | 来源:发表于2017-05-04 18:44 被阅读61次

    最近看了一些runtime的使用方法,之前一直静不下心来看,记录一下方便以后查看

    通过字符串获取方法

     SEL selector = NSSelectorFromString(@"getMethod");
    
    两个方法的替换
    BOOL result = class_replaceMethod([self class], @selector(method0), (IMP)method1, NULL);
    
    方法的交换

    method0方法的触发交换到method1接收

        SEL originalSelector = NSSelectorFromString(@"method0");
        SEL swizzledSelector = NSSelectorFromString(@"method1");
        Method originalMethod = class_getInstanceMethod([self class], originalSelector);
        Method swizzledMethod = class_getInstanceMethod([self class], swizzledSelector);
        method_exchangeImplementations(originalMethod, swizzledMethod);
    
    为类别新增一个属性

    类别新增属性需要关联当前的对象

       #pragma mark- 利用runtime为类别添加属性
    -(void)setProperty1:(NSString *)property1{
        //需要关联对象
        objc_setAssociatedObject(self, "property", property1, OBJC_ASSOCIATION_COPY_NONATOMIC);
    }
    -(NSString *)property1{
        return objc_getAssociatedObject(self, "property");
    }
    
    获取类所有的属性
       objc_property_t *propertys = class_copyPropertyList([self class], &copyIvarListCount);
        for (NSInteger i = 0; i<copyIvarListCount; i++) {
            objc_property_t property = propertys[i];
            const char *name = property_getName(property);
            NSLog(@">>>>>>class_copyPropertyList==:%s",name);
        }
      //需要释放
        free(propertys);
    
    获取整个类的实例方法的方法列表
       Method *methods = class_copyMethodList([self class], &copyIvarListCount);
        for (NSInteger i = 0; i<copyIvarListCount; i++) {
            Method method = methods[i];
            SEL name = method_getName(method);
            NSLog(@">>>>>>class_copyMethodList==:%@",NSStringFromSelector(name));
        }
      //需要释放
        free(methods);
    
    获取整个成员变量列表
    unsigned int copyIvarListCount = 0;
        Ivar *ivars = class_copyIvarList([self class], &copyIvarListCount);
        for (NSInteger i=0; i<copyIvarListCount; i++) {
            Ivar ivar = ivars[i];
            const char *name = ivar_getName(ivar);
            NSLog(@">>>>>>class_copyIvarList==:%s",name);
        }
        free(ivars);//需要释放
    
    获取所有继承的协议
    Protocol * __unsafe_unretained *protocals = class_copyProtocolList([self class], &copyIvarListCount);
        for (NSInteger i = 0; i<copyIvarListCount; i++) {
            Protocol *protocal = protocals[i];
            const char *name = protocol_getName(protocal);
            NSLog(@">>>>>>class_copyProtocolList==:%s",name);
        }
        free(protocals);
    

    相关文章

      网友评论

        本文标题:关于runtime的一些方法

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