Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS get property class

I'm trying to get a list of all the properties of an unknown class and the class of every property. By the moment I get a list of all the properties of an object(I do it recursively to get all of the superclasses). I inspired in this post

+ (NSArray *)classPropsFor:(Class)klass
{    
    NSLog(@"Properties for class:%@", klass);
    if (klass == NULL || klass == [NSObject class]) {
        return nil;
    }

    NSMutableArray *results = [[NSMutableArray alloc] init];

    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList(klass, &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        const char *propName = property_getName(property);
        if(propName) {
            NSString *propertyName = [NSString stringWithUTF8String:propName];
            [results addObject:propertyName];
        }
        NSArray* dict = [self classPropsFor:[klass superclass]];
        [results addObjectsFromArray:dict];
    }
    free(properties);

    return [NSArray arrayWithArray:results];
}

So now I want the class of every property and I do:

NSArray* properties = [PropertyUtil classPropsFor:[self class]];
for (NSString* property in properties) {
    id value= [self valueForKey:property];
    NSLog(@"Value class for key: %@ is %@", property, [value class]);
}

The problem is it works for NSStrings or but not for custom classes, for that it returns me null. I want to recursively create a dictionary that represents an object that can have other objects inside and as I thinks I need to know the class of every property, is that possible?

like image 823
Jpellat Avatar asked May 21 '12 14:05

Jpellat


People also ask

What does @property do in Objective C?

The goal of the @property directive is to configure how an object can be exposed. If you intend to use a variable inside the class and do not need to expose it to outside classes, then you do not need to define a property for it. Properties are basically the accessor methods.

What is property in iOS?

In its simplest form, a stored property is a constant or variable that's stored as part of an instance of a particular class or structure. Stored properties can be either variable stored properties (introduced by the var keyword) or constant stored properties (introduced by the let keyword).

What is type property in swift?

There are two kinds of properties: stored properties and computed properties. Stored properties are properties that are stored in the class's instance. Stored properties store constant and variable values. Computed properties are for creating custom get and set methods for stored properties.

How is property created in Python?

Creating Attributes With property() You can create a property by calling property() with an appropriate set of arguments and assigning its return value to a class attribute. All the arguments to property() are optional.


2 Answers

Just made a tiny method for this.

// Simple as.
Class propertyClass = [customObject classOfPropertyNamed:propertyName];

Could be optimized in many ways, but I love it.


Implementation goes like:

-(Class)classOfPropertyNamed:(NSString*) propertyName
{
    // Get Class of property to be populated.
    Class propertyClass = nil;
    objc_property_t property = class_getProperty([self class], [propertyName UTF8String]);
    NSString *propertyAttributes = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
    NSArray *splitPropertyAttributes = [propertyAttributes componentsSeparatedByString:@","];
    if (splitPropertyAttributes.count > 0)
    {
        // xcdoc://ios//library/prerelease/ios/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html
        NSString *encodeType = splitPropertyAttributes[0];
        NSArray *splitEncodeType = [encodeType componentsSeparatedByString:@"\""];
        NSString *className = splitEncodeType[1];
        propertyClass = NSClassFromString(className);
    }
    return propertyClass;
}

It is part of eppz!kit, within a developing object representer called NSObject+EPPZRepresentable.h. It actually does what you are to achieve originally.

// Works vica-versa.
NSDictionary *representation = [customObject dictionaryRepresentation];
CustomClass = [CustomClass representableWithDictionaryRepresentation:representation];

It encodes many types, iterate trough collections, represents CoreGraphics types, UIColors, also represent / reconstruct object references.


New version spits you back even C type names and named struct types as well:

NSLog(@"%@", [self typeOfPropertyNamed:@"index"]); // unsigned int
NSLog(@"%@", [self typeOfPropertyNamed:@"area"]); // CGRect
NSLog(@"%@", [self typeOfPropertyNamed:@"keyColor"]); // UIColor

Part of eppz!model, feel free to use method implementations at https://github.com/eppz/eppz.model/blob/master/eppz!model/NSObject%2BEPPZModel_inspecting.m#L111

like image 178
Geri Borbás Avatar answered Sep 20 '22 10:09

Geri Borbás


You should probably store the class (as a string) for each property at the same time as you store the propertyName. Maybe as a dictionary with property name as the key and class name as the value, or vice versa.

To get the class name, you can do something like this (put this right after you declare propertyName):

NSString* propertyAttributes = [NSString stringWithUTF8String:property_getAttributes(property)];
NSArray* splitPropertyAttributes = [propertyAttributes componentsSeparatedByString:@"\""];
if ([splitPropertyAttributes count] >= 2)
{
    NSLog(@"Class of property: %@", [splitPropertyAttributes objectAtIndex:1]);
}

The string handling code is because the attributes include a number of pieces of information - the exact details are specified here: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html

like image 41
Rob B Avatar answered Sep 18 '22 10:09

Rob B