获取一个类的所有属性和方法

2017-07-22  本文已影响24人  吓死宝宝了啊

调用下面两个方法必须引入#impot<objc/runtime.h>

1.获取所有的属性

- (NSArray *)getClassAttribute:(id)class

{

unsigned int count;

objc_property_t *properties = class_copyPropertyList([class class], &count);

NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];

for(int i = 0; i < count; i++)

{

const char  *propertyName = property_getName(properties[i]);

[propertiesArray addObject: [NSString stringWithUTF8String:propertyName]];

}

free(properties);

return propertiesArray;

}

2. 获取所有的方法

- (void)getAllMethodsFromClass:(id)obj {

u_int count;

Method * methList = class_copyMethodList([obj class], &count);//获取类的方法列表

for (int i = 0; i < count; i++) {

Method temp = methList[i];

//        IMP imp = method_getImplementation(temp);//有Method获取IMP指针

SEL name = method_getName(temp);//由Method获取SEL

const char * name_s = sel_getName(name);

int arguments = method_getNumberOfArguments(temp);//获取参数个数

const char * encoding = method_getTypeEncoding(temp);//有Method获取Encoding类型

NSLog(@"方法名:%@\n,参数个数:%d\n,编码方式:%@\n",[NSString stringWithUTF8String:name_s],

arguments,[NSString stringWithUTF8String:encoding]);

}

free(methList);

}

上一篇下一篇

猜你喜欢

热点阅读