Runtime是想要做好iOS开发,或者说是真正的深刻的掌握OC这门语言所必需理解的东西。最近在学习Runtime,有自己的一些心得,整理如下,
一为 查阅方便
二为 或许能给他人一些启发,
三为 希望得到大家对这篇整理不足之处的一些指点。
什么是Runtime
我们写的代码在程序运行过程中都会被转化成runtime的C代码执行,例如[target doSomething];会被转化成objc_msgSend(target, @selector(doSomething));。
OC中一切都被设计成了对象,我们都知道一个类被初始化成一个实例,这个实例是一个对象。实际上一个类本质上也是一个对象,在runtime中用结构体表示。
但是单纯的去调用又显得很麻烦,所有就自己简单的封装了几个方法,可以和大家一起交流学习
/**
获取类名
@param class <#class description#>
@return <#return value description#>
*/
+ (NSString *)fetchClassName:(Class)class{
const char *className = class_getName(class);
return [NSString stringWithUTF8String:className];
}
/**
获取成员变量
@param class <#class description#>
@return <#return value description#>
*/
+ (NSArray*)fetchIvaList:(Class)class{
unsigned int count = 0;
Ivar *ivarList = class_copyIvarList(class, &count);
NSMutableArray *mutaList = [[NSMutableArray alloc]initWithCapacity:count];
for (unsigned int i=0; i<count; i++) {
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:2];
const char*ivarName = ivar_getName(ivarList[i]);
const char*ivarType = ivar_getTypeEncoding(ivarList[i]);
dic[@"type"] = [NSString stringWithUTF8String:ivarType];
dic[@"ivarName"] = [NSString stringWithUTF8String:ivarName];
[mutaList addObject:dic];
}
free(ivarList);
return [NSArray arrayWithArray:mutaList];
/**
获取类的属性
@param NSArray <#NSArray description#>
@return <#return value description#>
*/
}
+ (NSArray*)fetchPropertyList:(Class)class{
unsigned int count =0;
objc_property_t*propertyList = class_copyPropertyList(class, &count);
NSMutableArray *mutableList = [[NSMutableArray alloc]initWithCapacity:count];
for (unsigned int i=0; i<count; i++) {
const char*propertyName = property_getName(propertyList[i]);
[mutableList addObject:[NSString stringWithUTF8String:propertyName]];
}
free(propertyList);
return [NSArray arrayWithArray:mutableList];
}
/**
类的实例方法
@param class <#class description#>
@return <#return value description#>
*/
+ (NSArray*)fetchMethodList:(Class)class{
unsigned int count = 0;
Method *methodList = class_copyMethodList(class, &count);
NSMutableArray *mutableList = [NSMutableArray arrayWithCapacity:count];
for (unsigned int i=0; i<count; i++) {
Method method = methodList[i];
SEL methodName = method_getName(method);
[mutableList addObject:NSStringFromSelector(methodName)];
}
free(methodList);
return [NSArray arrayWithArray:mutableList];
}