问题描述
有没有办法获得某种类型的类属性数组?例如,如果我有这样的界面
Is there a way to get an array of class properties of certain kind? For example if i have interface like this
@interface MyClass : NSObject
@property (strong,nonatomic) UILabel *firstLabel;
@property (strong,nonatomic) UILabel *secondLabel;
@end
我可以在不知道名称的情况下获得对这些标签的引用吗?
can i get the reference to those labels in implementation without knowing their name?
@implementation MyClass
-(NSArray*)getListOfAllLabels
{
?????
}
@end
我知道我可以用 [NSArray arrayWithObjects:firstLabel,secondLabel,nil]
轻松地做到这一点,但我想用某种类枚举来做到这一点,比如 for (UILabel*oneLabel in ???[self objects]???)
I know i can do it easily with [NSArray arrayWithObjects:firstLabel,secondLabel,nil]
, but i would like to do it with some kind of class enumeration like for (UILabel* oneLabel in ???[self objects]???)
推荐答案
更准确地说,如果我理解正确的话,您需要对属性进行动态的、运行时观察.做这样的事情(在 self 上实现这个方法,你想要内省的类):
So more precisely, you want dynamic, runtime observaion of the properties, if I got it correctly. Do something like this (implement this method on self, the class you want to introspect):
#import <objc/runtime.h>
- (NSArray *)allPropertyNames
{
unsigned count;
objc_property_t *properties = class_copyPropertyList([self class], &count);
NSMutableArray *rv = [NSMutableArray array];
unsigned i;
for (i = 0; i < count; i++)
{
objc_property_t property = properties[i];
NSString *name = [NSString stringWithUTF8String:property_getName(property)];
[rv addObject:name];
}
free(properties);
return rv;
}
- (void *)pointerOfIvarForPropertyNamed:(NSString *)name
{
objc_property_t property = class_getProperty([self class], [name UTF8String]);
const char *attr = property_getAttributes(property);
const char *ivarName = strchr(attr, 'V') + 1;
Ivar ivar = object_getInstanceVariable(self, ivarName, NULL);
return (char *)self + ivar_getOffset(ivar);
}
像这样使用它:
SomeType myProperty;
NSArray *properties = [self allPropertyNames];
NSString *firstPropertyName = [properties objectAtIndex:0];
void *propertyIvarAddress = [self getPointerOfIvarForPropertyNamed:firstPropertyName];
myProperty = *(SomeType *)propertyIvarAddress;
// Simpler alternative using KVC:
myProperty = [self valueForKey:firstPropertyName];
希望这会有所帮助.
这篇关于Objective-C 中的类属性列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!