gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:20:35 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com