在objective-c中,如何获取selfclass和所有superclass的属性列表?
In objective-c, how to get self class and all superclass's properties list?
有class个继承自NSObject。
@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;
然后我有一个class B继承自A
@interface B: A
@property(nonatomic, strong) NSValue* valueB;
@property(nonatomic, strong) NSArray* arrayB;
@end
我想知道B的所有属性(包括继承自B的属性)。如果我使用上面的方法,我只会得到 valueB
和 arrayB
。
如何获得valueB
、arrayB
和strA
、numA
?
@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
有class个继承自NSObject。
@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;
然后我有一个class B继承自A
@interface B: A
@property(nonatomic, strong) NSValue* valueB;
@property(nonatomic, strong) NSArray* arrayB;
@end
我想知道B的所有属性(包括继承自B的属性)。如果我使用上面的方法,我只会得到 valueB
和 arrayB
。
如何获得valueB
、arrayB
和strA
、numA
?
@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