Objective_C动态获取实例属性

转自:http://blog.csdn.net/favormm/article/details/9078935

本文主要围绕一个主题,如何动态获取实例属性的值?

objective_c动行时库已经有这样的功能。使用这些方法需要加头文件

  1. #import <objc/message.h>  

要用到的方法是

  1. objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount)    

从方法的名字可以看出作用:将一个类的属性copy出来。下面看一个例子,就知道如何使用了。

  1. @interface People : NSObject {    
  2. @property NSString *name;    
  3. @end   

现在我们动态获取它的属性名,与实例属性值。

  1. People *people = [[People alloc] init];  
  2. id peopleClass = objc_getClass("People");  
  3. unsigned int outCount, i;  
  4. objc_property_t *properties = class_copyPropertyList(peopleClass, &outCount);  
  5. for (i = 0; i < outCount; i++) {  
  6.     objc_property_t property = properties[i];  
  7.     NSString *propName = [NSString stringWithUTF8String:property_getName(property)];  
  8.     id value = [people <span style="font-family: Arial, Helvetica, sans-serif;"> </span>valueForKey:propName];  
  9.     fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property));  
  10. }  

是不是很酷呀,这样一来就可以获取所有的属性值。比如格式化对像为json或xml的时候就很有用。

但是如果类从其它的类继承过来的,父类的属性将不会被copy出来。如

  1. @interface People : NSObject {  
  2. @property NSString *name;  
  3. @end  
  4.       
  5. @interface Lender : People {  
  6. @property int employers;  
  7. @end  
  8.       
  9. Lender *leader = [[People alloc] init];  
  10. id leaderClass = objc_getClass("Lender");  
  11. unsigned int outCount, i;  
  12. objc_property_t *properties = class_copyPropertyList(leaderClass, &outCount);  
  13. for (i = 0; i < outCount; i++) {  
  14.     objc_property_t property = properties[i];  
  15.     NSString *propName = [NSString stringWithUTF8String:property_getName(property)];  
  16.     id value = [leader  valueForKey:propName];  
  17.     fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property));  
  18. }  

这儿可能获取employers的属性的值, 如何才能获取到父类的属性呢。

有两种方法。

1:用前面提到的方法分别获取子类与父类的属性列表。

2:声明一个Protocol, Protocol中有属性,然后获取Protocol中属性列表

第二个方法中要用到两个方法:

  1. objc_property_t *protocol_copyPropertyList(Protocol *proto, unsigned int *outCount)  
  2. Protocol *objc_getProtocol(const char *name)  

用法与前面掉到的都差不多,在此我就不多说了。

你可能感兴趣的:(Objective_C动态获取实例属性)