本文主要围绕一个主题,如何动态获取实例属性的值?
objective_c动行时库已经有这样的功能。使用这些方法需要加头文件
#import <objc/message.h>
objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount)
@interface People : NSObject { @property NSString *name; @end
现在我们动态获取它的属性名,与实例属性值。
People *people = [[People alloc] init];
id peopleClass = objc_getClass("People");
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(peopleClass, &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
NSString *propName = [NSString stringWithUTF8String:property_getName(property)];
id value = [people valueForKey:propName];
fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property));
}
但是如果类从其它的类继承过来的,父类的属性将不会被copy出来。如
@interface People : NSObject { @property NSString *name; @end @interface Lender : People { @property int employers; @end Lender *leader = [[People alloc] init]; id leaderClass = objc_getClass("Lender"); unsigned int outCount, i; objc_property_t *properties = class_copyPropertyList(leaderClass, &outCount); for (i = 0; i < outCount; i++) { objc_property_t property = properties[i]; NSString *propName = [NSString stringWithUTF8String:property_getName(property)]; id value = [leader valueForKey:propName]; fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property)); }
有两种方法。
1:用前面提到的方法分别获取子类与父类的属性列表。
2:声明一个Protocol, Protocol中有属性,然后获取Protocol中属性列表
第二个方法中要用到两个方法:
objc_property_t *protocol_copyPropertyList(Protocol *proto, unsigned int *outCount) Protocol *objc_getProtocol(const char *name)