打印Class
如果想要打印项目中所有的类包括系统类,可以使用objc_getClassList方法实现
具体代码如下:
{
int numClasses;
Class * classes = NULL;
//1.获取当前app运行时所有的类,包括系统创建的类和开发者创建的类的 个数
numClasses = objc_getClassList(NULL, 0);
if (numClasses > 0 )
{
//2.创建一个可以容纳numClasses个的大小空间
classes = (__unsafe_unretained Class *)malloc(sizeof(Class) * numClasses);
//3.重新获取具体类的列表和个数
numClasses = objc_getClassList(classes, numClasses);
//4.遍历
for (int i = 0; i < numClasses; i++) {
Class class = classes[i];
const char *className = class_getName(class);
NSLog(@"class name2 = %s", className);
}
free(classes);
}
}
有时我们只想打印项目中我们自己创建的类,这时需要使用到mach-O中的相关接口
{
unsigned int count;
const char **classes;
Dl_info info;
//1.获取app的路径
dladdr(&_mh_execute_header, &info);
//2.返回当前运行的app的所有类的名字,并传出个数
//classes:二维数组 存放所有类的列表名称
//count:所有的类的个数
classes = objc_copyClassNamesForImage(info.dli_fname, &count);
for (int i = 0; i < count; i++) {
//3.遍历并打印,转换Objective-C的字符串
NSString *className = [NSString stringWithCString:classes[i] encoding:NSUTF8StringEncoding];
Class class = NSClassFromString(className);
NSLog(@"class name = %@", class);
}
}
打印Class中的属性
{
unsigned int propertiesCount;
objc_property_t *properties = class_copyPropertyList(class, &propertiesCount);
for (int j = 0; j< propertiesCount; j++) {
objc_property_t property = properties[j];
NSLog(@" property name = %s",property_getName(property));
//获取属性特性,比如strong,weak,readonly
unsigned int outCount;
objc_property_attribute_t *attributeList = property_copyAttributeList(property, &outCount);
}
}
打印对象方法
{
unsigned int methodCount ;
Method *methods = class_copyMethodList(class, &methodCount);
for (int j = 0; j< methodCount; j++) {
Method method = methods[j];
NSLog(@" method name = %@ type = %s",NSStringFromSelector(method_getName(method)), method_getTypeEncoding(method));
}
}
打印类方法
ObjectiveC中一个任何一个类的定义都是对象。任何对象都是一个isa指针。普通对象的isa指针指向对象的Class。而Class的isa指针指向元类(meteClass)。而元类中保存了类方法列表。可以通过object_getClass
函数获取isa指向的对象。所以这里打印class的类方法只需要将打印对象方法中 class_copyMethodList(class,&methodCount)
改为
class_copyMethodList(object_getClass(class),&methodCount)
{
//获取类方法
methods = class_copyMethodList(object_getClass(class), &methodCount);
for (int j = 0; j< methodCount; j++) {
Method method = methods[j];
NSLog(@" method name = %@ type = %s",NSStringFromSelector(method_getName(method)), method_getTypeEncoding(method));
}
}
本文作者: ctinusdev
原文链接: https://ctinusdev.github.io/2017/08/05/RuntimeGetClassInfo/
转载请注明出处!