【问题标题】:In objective-c, how to get self class and all superclass's properties list?在objective-c中,如何获取自身类和所有超类的属性列表?
【发布时间】:2015-11-03 09:37:50
【问题描述】:

有一个继承自 NSObject 的类 A。

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

使用下面的代码很容易得到A的属性列表:

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;

然后我有一个继承自 A 的 B 类

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

我想知道 B 的所有属性(包括从 B 继承的)。如果我使用上面的方法,我只会得到valueBarrayB

我怎样才能得到valueBarrayBstrAnumA

【问题讨论】:

    标签: ios objective-c inheritance properties runtime


    【解决方案1】:
    @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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-05
      • 1970-01-01
      • 2019-01-12
      • 2017-09-19
      • 1970-01-01
      相关资源
      最近更新 更多