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

标签 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);

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

最佳答案

您可以通过以下方式查找类型:

 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

关于ios - 如何获取作为 UIView 子类的 ViewController 的所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21157114/

相关文章:

ios - 在 iPhone SE 上恢复 iPhone 4 备份后的 Web App 具有 iPhone 4 大小

ios - 在 ViewWillDisappear 上插入数据库

ios - 我是否需要做任何额外的工作来保护我的 iOS 应用程序中的 sqlite 数据库?

iphone - 如何用图片替换 UITableView?

Node.js - 搜索 "util"模块;识别核心模块

ios - UIButton 突出显示设置行为很奇怪

ios - 未声明的标识符不会消失

iphone - Cocoa Touch 中的音调生成

python - 判断函数是否是嵌套函数

java - 新的Object.getClass()