I'm trying to get the name of an instance variable from an Objective-C class. Say I have a class that looks like this:
@interface MyClass : NSObject
@property (nonatomic, copy) NSSNumber *myVar;
@end
Given myVar, I want to get "myVar". Then I could use it in a log like this:
MyClass *myObject = [[myClass alloc] init];
NSLog(@"The variable is named: %@", getVarName([myObject myVar]));
Then the log would say: The variable is named myVar
. Thank you for your help!
PS The reason I want to do this is to create a method for encoding variables for archiving. So when I write my encodeWithCoder
method I can just do something like this:
- (void)encodeWithCoder:(NSCoder *)aCoder
{
NSArray *varsForEncoding = [[NSArray alloc] initWithObjects:var1, var2, var3, nil];
for (NSObject *var in varsForEncoding)
{
[aCoder encodeObject:var forKey:getVarName(var)];
}
}
Then do the reverse in initWithCoder
. That would prevent typos screwing this up, e.g. using key @"myVar"
when encoding but typing @"mVar"
in the initializer.