Chris Wagner
Chris Wagner

Reputation: 21003

Get string value of class propery names in Objective-C

I have the following class definition.

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

Is it possible to obtain an array of NSString objects with all of the properties by name?

Array would look like this...

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

Solution (updated based on comment)

Thanks to Dave's answer I was able to write the following method to be used

- (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];
}

Upvotes: 4

Views: 3289

Answers (2)

Dave DeLong
Dave DeLong

Reputation: 243146

Yep! Here you go:

#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);

Warning: code typed in browser.

Upvotes: 5

Alex
Alex

Reputation: 26859

You could call dictionaryWithValuesForKeys: and then call the allValues method on that dictionary to get an array of values. Note that you'll need to convert the non-NSString properties to strings yourself.

Upvotes: 2

Related Questions