0

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.

2 Answers2

7

You can try with this method:

//returns nil if property is not found
-(NSString *)propertyName:(id)property {  
  unsigned int numIvars = 0;
  NSString *key=nil;
  Ivar * ivars = class_copyIvarList([self class], &numIvars);
  for(int i = 0; i < numIvars; i++) {
    Ivar thisIvar = ivars[i];
    if ((object_getIvar(self, thisIvar) == property)) {
        key = [NSString stringWithUTF8String:ivar_getName(thisIvar)];
        break;
    }
  } 
  free(ivars);
  return key;
}  

(source)

Community
  • 1
  • 1
sergio
  • 68,819
  • 11
  • 102
  • 123
0

Just use a single line of code as this.

#define NSLogVariable(x) NSLog( @"Variable : %s = %@",#x,x)

define it along with the headers as a macro and use it anywhere. eg:

NSString *myObj=@"abcd";
NSLogVariable(myObj);

it will display

Variable : myObj = "abcd"

Hope it help some one.

abhimuralidharan
  • 5,752
  • 5
  • 46
  • 70