点击上方“
程序员大咖
”,选择“置顶公众号”
关键时刻,第一时间送达!
Objective-C 是一个动态语言,它需要一个运行时系统来动态的创建类和对象、进行消息传递和转发。关于Runtime的知识大家可以参看
Apple开源的Runtime代码
和
Rumtime编程指南
。
本文总结一些其常用的方法。
我们先创建一个测试Demo如下图,其中TestClass是一个测试类,TestClass+Category是它的一个分类,NSObject+Runtime封装了一些Runtime的方法。大家可以在这里下载Demo。
Demo
下面是几个类的主要部分:
TestClass.h
TestClass.m
TestClass+Category.h
TestClass+Category.m
接下来我们就来看看NSObject+Runtime中的内容,其对Runtime常用的方法进行了简单的封装:
别着急,我们一个一个看。
1、获取成员变量
下面这个方法就是获取类的成员变量列表,其中包括属性生成的成员变量。我们可以用ivar_getTypeEncoding()来获取成员变量的类型,用ivar_getName()来获取成员变量的名称:
+ (NSArray *)fetchIvarList
{
unsigned int count = 0;
Ivar *ivarList = class_copyIvarList(self, &count);
NSMutableArray *mutableList = [NSMutableArray arrayWithCapacity: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];
[mutableList addObject:dic];
}
free(ivarList);
return [NSArray arrayWithArray:mutableList];
}
使用[TestClass fetchIvarList]方法获取TestClass类的成员变量结果:
TestClass的成员变量列表
2、获取属性列表
下面这个方法获取的是属性列表,包括私有和公有属性,也包括分类中的属性:
+ (NSArray *)fetchPropertyList
{
unsigned int count = 0;
objc_property_t *propertyList = class_copyPropertyList(self, &count);
NSMutableArray *mutableList = [NSMutableArray arrayWithCapacity: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];
}
使用[TestClass fetchPropertyList]获取TestClass的属性列表结果:
TestClass的属性列表
3、获取实例方法
下面这个方法就是获取类的实例方法列表,包括getter, setter, 分类中的方法等:
+ (NSArray *)fetchInstanceMethodList
{
unsigned int count = 0;
Method *methodList = class_copyMethodList(self, &count);
NSMutableArray *mutableList = [NSMutableArray arrayWithCapacity:count];
for (unsigned int i = 0; i < count; i++)
{
Method method = methodList[i];
SEL methodName = method_getName(method);