2

我正在寻找一种从方法内部获取属性名称作为 StringValue 的方法。

让我们说:

我的班级有来自 UILabel 类型的 X 子视图。

@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_getInstanceVariableobject_getIvarproperty_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

4

2 回答 2

0

未经测试的代码来自在 Objective-C 中获取对象的属性数组

id currentClass = [self class];
NSString *propertyName;
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(currentClass, &outCount);
for (i = 0; i < outCount; i++) {
    objc_property_t property = properties[i];
    propertyName = [NSString stringWithCString:property_getName(property)];
    NSLog@("The propertyName is %@",propertyName);
}
于 2012-06-06T11:19:14.263 回答
0

无需运行循环即可获取特定属性名称的简便方法

可以说自定义对象如下

@interface StoreLocation : NSObject
@property (nonatomic, strong) NSString *city;
@property (nonatomic, strong) NSNumber *lat;
@property (nonatomic, strong) NSNumber *lon;
@property (nonatomic, strong) NSString *street;
@property (nonatomic, strong) NSString *state;
@property (nonatomic, strong) NSString *code;
@end


@interface AppleStore : NSObject

@property (nonatomic, strong) StoreLocation *storeLocation;

@end

下面的目标宏将获得所需的结果

#define propertyKeyPath(property) (@""#property)
#define propertyKeyPathLastComponent(property) [[(@""#property)componentsSeparatedByString:@"."] lastObject]

使用下面的代码获取属性名称

NSLog(@"%@", propertyKeyPath(appleStore.storeLocation)); //appleStore.storeLocation
NSLog(@"%@", propertyKeyPath(appleStore.storeLocation.street)); //appleStore.storeLocation.street
NSLog(@"%@", propertyKeyPathLastComponent(appleStore.storeLocation)); //storeLocation
NSLog(@"%@", propertyKeyPathLastComponent(appleStore.storeLocation.street)); //street

来源:http ://www.g8production.com/post/78429904103/get-property-name-as-string-without-using-the-runtime

于 2014-07-25T04:28:33.507 回答