关于runtime的一些方法

最近看了一些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], ©IvarListCount);
    for (NSInteger i = 0; i>>>>>class_copyPropertyList==:%s",name);
    }
  //需要释放
    free(propertys);
获取整个类的实例方法的方法列表
   Method *methods = class_copyMethodList([self class], ©IvarListCount);
    for (NSInteger i = 0; i>>>>>class_copyMethodList==:%@",NSStringFromSelector(name));
    }
  //需要释放
    free(methods);
获取整个成员变量列表
unsigned int copyIvarListCount = 0;
    Ivar *ivars = class_copyIvarList([self class], ©IvarListCount);
    for (NSInteger i=0; i>>>>>class_copyIvarList==:%s",name);
    }
    free(ivars);//需要释放
获取所有继承的协议
Protocol * __unsafe_unretained *protocals = class_copyProtocolList([self class], ©IvarListCount);
    for (NSInteger i = 0; i>>>>>class_copyProtocolList==:%s",name);
    }
    free(protocals);

你可能感兴趣的:(关于runtime的一些方法)