获取/打印类的属性列表

xCode 6以前 , 在API中会有私有属性共有属性的划分,而之后的版本中无法在API中查看某一类的私有属性 , 通过运行时的特性可以帮助我们获取某一个类的全部方法、属性、成员变量以及所有的协议, 当我们获取到私有属性后,遍可以通过KVC进行设置
【获取/打印类的属性列表】1.导入头文件#import
2.可以定义一个继承自NSObject的工具类,也可以直接将方法粘贴在所需要的类中直接调用

+ (NSArray *)js_objProperties{/* class_copyIvarList(__unsafe_unretained Class cls, unsigned int *outCount)成员变量 class_copyMethodList(__unsafe_unretained Class cls, unsigned int *outCount)方法 class_copyPropertyList(__unsafe_unretained Class cls, unsigned int *outCount)属性 class_copyProtocolList(__unsafe_unretained Class cls, unsigned int *outCount)协议 *//*调用运行时方法,取得类的属性列表返回值 : 所有属性的数组 (是一个C数组指针:C语言中数组的名字就是首元素的地址) 参数 1 :要获取的类 参数 2 :类属性的个数指针 */ unsigned int count = 0; objc_property_t *propertyList = class_copyPropertyList([self class], &count); // 用来存放所有属性的数组 NSMutableArray *mArr = [NSMutableArray array]; // 遍历所有属性 for (unsigned int i = 0; i < count; i ++) {// 1. 从数组中取得所有属性 objc_property_t property = propertyList[i]; const char *cName = property_getName(property); NSString *propertyName = [NSString stringWithCString:cName encoding:NSUTF8StringEncoding]; [mArr addObject:propertyName]; }// C语言中 retain/create/copy 都需要release, 可以option+click方法名,通过API描述中找到释放方法 // 例如这里的提示: You must free the array with free(). free(propertyList); return mArr.copy; }/** *打印类的所有属性 * *@param className 类名 */ + (void)js_logPrivatePropertiesWithClass:(NSString *)className{unsigned int count = 0; objc_property_t *properties = class_copyPropertyList([NSClassFromString(className) class], &count); for (int i=0; i

    推荐阅读