ObjC获取属性名称

时间:2012-06-06 10:36:32

标签: objective-c ios xcode cocoa runtime

我正在寻找一种从方法内部获取属性名称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_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 ”等等。


解决

正如在格雷弗的回复中描述的解决方案是: class_copyIvarList,返回Ivars的名称。

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/1228534Objective C Introspection/Reflection

2 个答案:

答案 0 :(得分:0)

来自Getting an array of properties for an object in 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);
}

答案 1 :(得分: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

下面的Objective宏将获得所需的结果

#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