我正在尝试动态确定 Objective-C 中属性的类型。根据我在本网站和其他地方读到的内容,我相信我正在做正确的事情。但是,我的代码不起作用。
下面的代码片段演示了这个问题。尝试获取“backgroundColor”和“frame”的属性信息(这两个属性都是 UIView 的有效属性)失败(class_getProperty() 返回 NULL):
id type = [UIView class];
objc_property_t backgroundColorProperty = class_getProperty(type, "backgroundColor");
fprintf(stdout, "backgroundColorProperty = %d\n", (int)backgroundColorProperty); // prints 0
objc_property_t frameProperty = class_getProperty(type, "frame");
fprintf(stdout, "frameProperty = %d\n", (int)frameProperty); // prints 0
枚举所描述的属性here https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html也没有产生预期的结果。下面的代码:
NSLog(@"Properties for %@", type);
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(type, &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property));
}
生成此输出:
2012-03-09 13:18:39.108 IOSTest[2921:f803] Properties for UIView
caretRect T{CGRect={CGPoint=ff}{CGSize=ff}},R,N,G_caretRect
gesturesEnabled Tc,N
deliversTouchesForGesturesToSuperview Tc,N
skipsSubviewEnumeration Tc,N
viewTraversalMark Tc,N
viewDelegate T@"UIViewController",N,G_viewDelegate,S_setViewDelegate:
inAnimatedVCTransition Tc,N,GisInAnimatedVCTransition
monitorsSubtree Tc,N,G_monitorsSubtree,S_setMonitorsSubtree:
backgroundColorSystemColorName T@"NSString",&,N,G_backgroundColorSystemColorName,S_setBackgroundColorSystemColorName:
userInteractionEnabled Tc,N,GisUserInteractionEnabled
tag Ti,N,V_tag
layer T@"CALayer",R,N,V_layer
缺少记录的属性,例如“backgroundColor”、“frame”和其他属性,而包含未记录的属性,例如“caretRect”和“gesturesEnabled”。
任何帮助将非常感激。如果相关的话,我在 iOS 模拟器上看到了这种行为。我不知道在实际设备上是否会发生同样的情况。
谢谢,
格雷格