hzwzw
hzwzw

Reputation: 1100

In objective-c, how to get self class and all superclass's properties list?

There is class A inherited from NSObject.

@interface A: NSObject  
 @property(nonatomic, strong) NSNumber* numA;
 @property(nonatomic, strong) NSString* strA;
@end

It's easy to get the property list of A using the code below:

unsigned int num_props;
objc_property_t* prop_list;
NSMutableSet* set = [NSMutableSet New];
prop_list = class_copyPropertyList(self, &num_props);
for(unsigned int i = 0; i < num_props; i++) {
  NSString* propName = [NSString stringWithFormat:@"%s", property_getName(prop_list[i])];
 [self customMethod];
}
free(prop_list);
return set;

Then I have a class B inherited from A

@interface B: A
 @property(nonatomic, strong) NSValue* valueB;
 @property(nonatomic, strong) NSArray* arrayB;
@end

I want to know all B's properties(including the inherited from B). If I use the method above I only get valueB and arrayB.

How could I get valueB, arrayB, and strA, numA?

Upvotes: 0

Views: 984

Answers (1)

hzwzw
hzwzw

Reputation: 1100

@implementation A
+ (NSSet *)allPropertys {
    NSMutableSet* result = [NSMutableSet new];
    Class observed = self;
    while ([observed isSubclassOfClass:[A class]]) {
     [self propertyForClass: observed withSet: &result];
     observed = [observed superclass];
    }
   return result;
  }

+ (void)propertyForClass: (Class)class withSet: (NSMutableSet **)result {
  unsigned int num_props;
  objc_property_t* prop_list;
  prop_list = class_copyPropertyList(class, &num_props);

  for(unsigned int i = 0; i < num_props; i++) {
    NSString * propName = [NSString stringWithFormat:@"%s", property_getName(prop_list[i])];
    [class customMethod: propName];
    [*result addObject: propName];
  }
  free(prop_list);
}
@end

Upvotes: 3

Related Questions