代码之家  ›  专栏  ›  技术社区  ›  ashcatch

objective-c 2.0:class_CopyPropertyList(),如何从类别中列出属性

  •  19
  • ashcatch  · 技术社区  · 17 年前

    我试图列出一个Objective-C类的所有属性,如 Objective-C 2.0 Runtime Programming Guide :

    id LenderClass = objc_getClass("UIView");
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList(LenderClass, &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property));
    }
    

    但这只列出了三个属性:

    userInteractionEnabled Tc,GisUserInteractionEnabled
    layer T@"CALayer",R,&,V_layer
    tag Ti,V_tag
    

    查看uiview.h的头文件,这是类中直接声明的三个属性。其他uiview属性是通过类别添加的。

    如何获取类的所有属性,包括来自类别的属性?

    我用iPhone模拟器(iPhone SDK 2.2.1),顺便说一句(以防这很重要)。

    2 回复  |  直到 13 年前
        1
  •  14
  •   Jim Dovey    17 年前

    基于此处的测试,使用时将显示类别中的属性 class_copyPropertyList . 看起来您在uiview上看到的属性只是 描述 作为公共头中的属性,在构建uikit本身时不实际声明为此类属性。可能他们采用了属性语法来加快公共头的创建速度。

    作为参考,这里是我的测试项目:

    #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;
    }
    

    输出结果如下:

    str2 T@"NSString",C
    str1 T@"NSString",C,Vstr1
    
        2
  •  7
  •   Chris Hatton    13 年前

    是的,class_CopyPropertyList函数返回在类别中定义的属性。

    这里所发生的是,它只返回在给定类级别定义的属性——所以您只看到在uiview中定义的三个属性,而在uiresponder和nsObject祖先中定义的属性(普通或类别)都没有。

    为了实现完整的继承列表,必须通过class.superclass引用循环遍历祖先,并聚合class_CopyPropertyList的结果。然后,您将看到,例如,在nsObject的uikits可访问性类别中定义的各种属性。

    我其实是来这里想办法 排除 从这些结果中分类定义的属性!