Go to get the name of an object property, can be boring using the Objective-C runtime reference.
Fortunately there is a quick way to get it. Assume that you have an object named “appleStore” that has a property named “storeLocation”.
StoreLocation is another object with some properties: “city”, “lat”, “lon”, “street”, “state”, “code”.
@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 |
|---|
Since you are one of the best Objective-C developers in the world, you know that a property is composed by a keypath.
So, if you wanna access to the “storeLocation” property value or to the “street” property value, you must write the code below.
How you know, the keypath separator is the char “.” so, how can you print the property name???
AppleStore *appleStore = [AppleStore new]; //...... NSLog(@"%@", appleStore.storeLocation); //print the property value NSLog(@"%@", appleStore.storeLocation.street); //print the property value |
|---|
The quick way is to define two Objective-C macros that can help you.
Just on top of your class, above the @interface declaration, write the code below.
#define propertyKeyPath(property) (@""#property) #define propertyKeyPathLastComponent(property) [[(@""#property) componentsSeparatedByString:@"."] lastObject] |
|---|
Finally, get the property name or the last component property name, using the code below in your methods.
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
|
|---|