我想使用反射来获取ViewController
的所有属性,它们是UIView
的子类。
我有这个方法来获取所有属性:
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);
但是如何找到这个属性的类型?
答案 0 :(得分:1)
您可以通过以下方式找到类型:
const char * propertyAttrs = property_getAttributes(property);
输出如下:
(lldb) p propertyAttrs
(const char *) $2 = 0x0065f74d "T@"UICollectionView",W,N,V_collectionView"
其中"T@"UICollectionView"
是属性类型。
<强>更新强>
我玩过它。这段代码不理想,测试不好,但有效:
const char * property_getTypeString( objc_property_t property )
{
const char * attrs = property_getAttributes( property );
if ( attrs == NULL )
return ( NULL );
static char buffer[256];
const char * e = strchr( attrs, ',' );
if ( e == NULL )
return ( NULL );
int len = (int)(e - attrs);
memcpy( buffer, attrs, len );
buffer[len] = '\0';
return ( buffer );
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
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)];
const char * typeString = property_getTypeString(property);
NSString *type = [NSString stringWithUTF8String:typeString];
NSCharacterSet *delimiters = [NSCharacterSet characterSetWithCharactersInString:@"\""];
NSArray *splitString = [type componentsSeparatedByCharactersInSet:delimiters];
Class classType = NSClassFromString(splitString[1]);
BOOL result = [classType isSubclassOfClass:UIView.class];
[rv addObject:name];
}
free(properties);
}
函数 property_getTypeString 来自这里:https://github.com/AlanQuatermain/aqtoolkit
答案 1 :(得分:0)
也许您可以查看runtime.h
property_getAttributes(property_name)
作为一个例子:
// will return what type the property is
const char * propertyAttrs = property_getAttributes(property);