Objective-C 2.0: class_copyPropertyList(), how to list properties from categories

后端 未结 2 1850
死守一世寂寞
死守一世寂寞 2020-12-15 06:04

I tried to list all properties of an Objective-C class like described in the Objective-C 2.0 Runtime Programming Guide:

id LenderClass = objc_getClass(\"UIVi         


        
相关标签:
2条回答
  • 2020-12-15 06:49

    Based on my tests here, properties from categories will show up when using class_copyPropertyList. It looks as though the properties you're seeing on UIView are only described as properties in the public headers, not actually declared as such when building the UIKit itself. Probably they adopted the property syntax to make the creation of the public headers a little quicker.

    For reference, here's my test project:

    #import <Foundation/Foundation.h>
    #import <objc/runtime.h>
    
    @interface TestClass : NSObject
    {
        NSString * str1;
        NSString * str2;
    }
    @property (nonatomic, copy) NSString * str1;
    @end
    
    @interface TestClass (TestCategory)
    @property (nonatomic, copy) NSString * str2;
    @end
    
    @implementation TestClass
    @synthesize str1;
    @end
    
    @implementation TestClass (TestCategory)
    
    // have to actually *implement* these functions, can't use @synthesize for category-based properties
    - (NSString *) str2
    {
        return ( str2 );
    }
    
    - (void) setStr2: (NSString *) newStr
    {
        [str2 release];
        str2 = [newStr copy];
    }
    
    @end
    
    int main (int argc, const char * argv[])
    {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
        unsigned int outCount, i;
        objc_property_t *properties = class_copyPropertyList([TestClass class], &outCount);
        for (i = 0; i < outCount; i++) {
            objc_property_t property = properties[i];
            fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property));
        }
    
        [pool drain];
        return 0;
    }
    

    And here's the output:

    str2 T@"NSString",C
    str1 T@"NSString",C,Vstr1
    
    0 讨论(0)
  • 2020-12-15 06:51

    Yes, the class_copyPropertyList function does return properties defined in categories.

    What's going on here, is that it only returns properties defined at the given class level - so you are only seeing the three properties defined in UIView, and none of the properties (normal or category) that are defined in the UIResponder and NSObject ancestors.

    In order to achieve the full inherited listing; you must loop up through the ancestors via the Class.superclass reference and aggregate the results from class_copyPropertyList. Then you will see, for example, the various properties defined in UIKits Accessibility category for NSObject.

    I actually came here looking for a way to exclude the properties defined in categories from these results!

    0 讨论(0)
提交回复
热议问题