在Objective-C中获取类属性名称的字符串值

时间:2010-06-08 21:28:58

标签: objective-c iphone

我有以下类定义。

Contact.h

#import <CoreData/CoreData.h>


@interface Contact :  NSManagedObject  
{
}

@property (nonatomic, retain) NSString * City;
@property (nonatomic, retain) NSDate * LastUpdated;
@property (nonatomic, retain) NSString * Country;
@property (nonatomic, retain) NSString * Email;
@property (nonatomic, retain) NSNumber * Id;
@property (nonatomic, retain) NSString * ContactNotes;
@property (nonatomic, retain) NSString * State;
@property (nonatomic, retain) NSString * StreetAddress2;
@property (nonatomic, retain) NSDate * DateCreated;
@property (nonatomic, retain) NSString * FirstName;
@property (nonatomic, retain) NSString * Phone1;
@property (nonatomic, retain) NSString * PostalCode;
@property (nonatomic, retain) NSString * Website;
@property (nonatomic, retain) NSString * StreetAddress1;
@property (nonatomic, retain) NSString * LastName;

@end

是否可以通过名称获取具有所有属性的NSString对象数组?

数组看起来像这样......

[@"City", @"LastUpdated", @"Country", .... ]

解决方案(根据评论更新)

感谢Dave的回答,我能够编写以下方法

- (NSMutableArray *) propertyNames: (Class) class { 
    NSMutableArray *propertyNames = [[NSMutableArray alloc] init];
    unsigned int propertyCount = 0;
    objc_property_t *properties = class_copyPropertyList(class, &propertyCount);

    for (unsigned int i = 0; i < propertyCount; ++i) {
        objc_property_t property = properties[i];
        const char * name = property_getName(property);
        [propertyNames addObject:[NSString stringWithUTF8String:name]];
    }
    free(properties);
    return [propertyNames autorelease];
}

2 个答案:

答案 0 :(得分:5)

是的!你走了:

#import <objc/runtime.h>

//somewhere:
unsigned int propertyCount = 0;
objc_property_t * properties = class_copyPropertyList([self class], &propertyCount);

NSMutableArray * propertyNames = [NSMutableArray array];
for (unsigned int i = 0; i < propertyCount; ++i) {
  objc_property_t property = properties[i];
  const char * name = property_getName(property);
  [propertyNames addObject:[NSString stringWithUTF8String:name]];
}
free(properties);
NSLog(@"Names: %@", propertyNames);

警告:在浏览器中输入代码。

答案 1 :(得分:2)

您可以调用dictionaryWithValuesForKeys:然后调用该字典上的allValues方法来获取值数组。请注意,您需要自己将非NSString属性转换为字符串。