【发布时间】:2012-06-06 10:36:32
【问题描述】:
我正在寻找一种从方法内部将属性名称作为 StringValue 获取的方法。
让我们说:
我的班级有 X 个来自 UILabel 类型的子视图。
@property (strong, nonatomic) UILabel *firstLabel;
@property (strong, nonatomic) UILabel *secondLabel;
[...]
等等。
在 foo 方法中,视图迭代如下:
-(void) foo
{
for (UIView *view in self.subviews) {
if( [view isKindOfClass:[UILabel class]] ) {
/*
codeblock that gets the property name.
*/
}
}
}
结果应该是这样的:
THE propertyName(NSString) OF view(UILabel) IS "firstLabel"
我尝试了 class_getInstanceVariable、object_getIvar 和 property_getName,但均未成功。
例如以下代码:
[...]
property_getName((void*)&view)
[...]
返回:
<UILabel: 0x6b768c0; frame = (65 375; 219 21); text = 'Something'; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x6b76930>>
但我正在寻找这种结果:“firstLabel”、“secondLabel”等等。
已解决
正如在graver的回复中描述的那样,解决方案是: class_copyIvarList 返回 Ivar 的名称。
Ivar* ivars = class_copyIvarList(clazz, &count);
NSMutableArray* ivarArray = [NSMutableArray arrayWithCapacity:count];
for (int i = 0; i < count ; i++)
{
const char* ivarName = ivar_getName(ivars[i]);
[ivarArray addObject:[NSString stringWithCString:ivarName encoding:NSUTF8StringEncoding]];
}
free(ivars);
查看帖子: https://stackoverflow.com/a/2302808/1228534 和 Objective C Introspection/Reflection
【问题讨论】:
-
这正是我要找的! class_copyIvarList 完成了这项工作!非常感谢!!!
-
从您的描述中,我仍然不明白 class_copyIvarList 如何允许您提取指向给定对象的属性名称,仅使用对象和“自我”来使用。如果您回答自己的问题并指出解决问题的步骤,您会得到我的 +1。
标签: objective-c ios xcode cocoa runtime