Anyway to get string from variable name?

Solution 1:

As easy as

#define VariableName(arg) (@""#arg)

Then you do:

NSObject *obj;
NSString *str = VariableName(obj);
NSLog(@"STR %@", str);//obj

Solution 2:

You can get the names of a class's instance variables with the Objective-C runtime API function class_copyIvarList. However, this is rather involved, rarely done and almost never the best way to accomplish something. If you have a more specific goal in mind than mere curiosity, it might be a good idea to ask about how to accomplish it in Objective-C.

Also, incidentally, person.name doesn't specify an instance variable in Objective-C — it's a property call. The instance variable would be person->name.

Solution 3:

You might use preprocessor stringification and a bit of string twiddling:

NSUInteger lastIndexAfter(NSUInteger start, NSString *sub, NSString *str) {
    NSRange found = [str rangeOfString:sub options:NSBackwardsSearch];
    if(found.location != NSNotFound) {
        NSUInteger newStart = NSMaxRange(found);
        if(newStart > start)
            return newStart;
    }
    return start;
}

NSString *lastMember(NSString *fullName) {
    if(!fullName) return nil;

    NSUInteger start = 0;
    start = lastIndexAfter(start, @".", fullName);
    start = lastIndexAfter(start, @"->", fullName);

    return [fullName substringFromIndex: start];
}

#define NSStringify(v) (@#v)
#define _NameofVariable_(v) lastMember(NSStringify(v))