如何获取作为UIView的子类的ViewController的所有属性

时间:2014-01-16 08:50:27

标签: ios objective-c reflection uiview

我想使用反射来获取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);

但是如何找到这个属性的类型?

2 个答案:

答案 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);