Reputation: 13947
I want to use reflection to get all the properties of a ViewController
, that are subclasses of UIView
.
I have this method to get all the properties:
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);
But how do I find which type this property is?
Upvotes: 1
Views: 463
Reputation: 2954
You can find type via:
const char * propertyAttrs = property_getAttributes(property);
The output will be like the following:
(lldb) p propertyAttrs
(const char *) $2 = 0x0065f74d "T@"UICollectionView",W,N,V_collectionView"
Where "T@"UICollectionView"
is property type.
UPDATE
I've played with it. This code is not ideal and not tested well, but it works:
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);
}
The function property_getTypeString is borrowed from here: https://github.com/AlanQuatermain/aqtoolkit
Upvotes: 1
Reputation: 2451
Maybe you can check runtime.h
property_getAttributes(property_name)
as an example:
// will return what type the property is
const char * propertyAttrs = property_getAttributes(property);
Upvotes: 0