gpt4 book ai didi

iphone - Objective-C 2.0 : class_copyPropertyList(), 如何从类别中列出属性

转载 作者:太空狗 更新时间:2023-10-30 03:14:24 24 4
gpt4 key购买 nike

我试图列出 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) 试过了。 (如果这很重要)。

最佳答案

根据我在这里的测试,当使用 class_copyPropertyList 时,来自类别的属性将会显示。看起来您在 UIView 上看到的属性只是被描述为公共(public) header 中的属性,在构建 UIKit 本身时并没有实际声明。可能他们采用了属性语法来更快地创建公共(public) header 。

作为引用,这是我的测试项目:

#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

关于iphone - Objective-C 2.0 : class_copyPropertyList(), 如何从类别中列出属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/848636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com