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.

1

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Worked great, thanks. I just had to link to libobjc.dylib and import <objc/runtime.h>.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.