iOS get property class

后端 未结 4 2203
粉色の甜心
粉色の甜心 2021-02-06 09:55

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 recurs

4条回答
  •  無奈伤痛
    2021-02-06 10:26

    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

提交回复
热议问题