Get string value of class property 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 get an array of NSString objects with all properties by name?

The array will look like this:

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

Solution (updated based on comment)

Thanks to Dave's answer, I was able to write the following method, which will 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]; } 
+4
source share
2 answers

Oops! Here you are:

 #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 entered in the browser.

+5
source

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

+2
source

Source: https://habr.com/ru/post/1312262/


All Articles