最近看了一些runtime的使用方法,之前一直靜不下心來看,記錄一下方便以后查看
通過字符串獲取方法
SEL selector = NSSelectorFromString(@"getMethod");
兩個方法的替換
BOOL result = class_replaceMethod([self class], @selector(method0), (IMP)method1, NULL);
方法的交換
method0方法的觸發(fā)交換到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);
為類別新增一個屬性
類別新增屬性需要關聯(lián)當前的對象
#pragma mark- 利用runtime為類別添加屬性
-(void)setProperty1:(NSString *)property1{
//需要關聯(lián)對象
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<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], ©IvarListCount);
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], ©IvarListCount);
for (NSInteger i=0; i<copyIvarListCount; i++) {
Ivar ivar = ivars[i];
const char *name = ivar_getName(ivar);
NSLog(@">>>>>>class_copyIvarList==:%s",name);
}
free(ivars);//需要釋放
獲取所有繼承的協(xié)議
Protocol * __unsafe_unretained *protocals = class_copyProtocolList([self class], ©IvarListCount);
for (NSInteger i = 0; i<copyIvarListCount; i++) {
Protocol *protocal = protocals[i];
const char *name = protocol_getName(protocal);
NSLog(@">>>>>>class_copyProtocolList==:%s",name);
}
free(protocals);