ash*_*tch 19 iphone cocoa objective-c
我试图列出Objective-C类的所有属性,如Objective-C 2.0运行时编程指南中所述:
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));
}
Run Code Online (Sandbox Code Playgroud)
但是这只列出了三个属性:
userInteractionEnabled Tc,GisUserInteractionEnabled
layer T@"CALayer",R,&,V_layer
tag Ti,V_tag
Run Code Online (Sandbox Code Playgroud)
查看UIView.h的头文件,这些是在类中直接声明的三个属性.其他UIView属性通过类别添加.
如何获取课程的所有属性,包括来自类别的属性?
我尝试使用iPhone模拟器(iPhone SDK 2.2.1),顺便说一句.(如果这很重要).
Jim*_*vey 14
根据我在此处的测试,使用时会显示类别中的属性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;
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
str2 T@"NSString",C
str1 T@"NSString",C,Vstr1
Run Code Online (Sandbox Code Playgroud)
是的,class_copyPropertyList函数确实返回在类别中定义的属性.
这里发生的是,它只返回在给定类级别定义的属性 - 因此您只看到UIView中定义的三个属性,而没有在UIResponder和NSObject祖先中定义的属性(普通或类别).
为了实现完全继承的上市; 您必须通过Class.superclass引用遍历祖先并聚合class_copyPropertyList的结果.然后,您将看到,例如,NIKbject的UIKits可访问性类别中定义的各种属性.
我实际上来到这里寻找一种方法从这些结果中排除类别中定义的属性!