2

How can I convert a variable name into a string?

Example:

From this:

NSString *someVariable
int otherVariable

I want to get a NSString with the actual name of the variable, no matter what type it is.
So, for the two variables above I would want to get their names (someVariable, otherVariable).

3 Answers 3

5

I managed to solve my problem with this code snippet:

Import the objc runtime
#import <objc/runtime.h>

and you can enumerate the properties with:

- (NSArray *)allProperties
{
    unsigned count;
    objc_property_t *properties = class_copyPropertyList([self class], &count);

    NSMutableArray *rv = [NSMutableArray array];

    unsigned i;
    for (i = 0; i < count; i++)
    {
        objc_property_t property = properties[i];
        NSString *name = [NSString stringWithUTF8String:property_getName(property)];
        [rv addObject:name];
    }

    free(properties);

    return rv;
}

Hope it helps someone.

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

Comments

1

Just add " ... " around the variable name. i.e.

"someVariable"
"otherVariable"

to get the string (as a const char*.) If you want an NSString*, use

@"someVariable"
@"otherVariable"

Within a macro, you can use the construction #... to put the quote ... unquote around a macro variable, e.g.

#define MyLog(var) NSLog(@"%s=%@", #var, var)

so that

MyLog(foo);

is expanded to

NSLog(@"%s=%@", "foo", foo);

Comments

0

These are C declarations, and C does not have the introspection capability to give you what you want.

You could probably write a preprocessor macro that would both declare a variable and also declare and initialize a second variable with the name of the first.

But this begs the question of why you need this level of introspection at all.

1 Comment

I'm reading some nodes from a json and I use the node names as variables in my application. I do this because I have for each node three similar names (node, node_waiting, node_rejected) so I'm hopping to use the variable name in such a way that I don't have to create 3 times the number of variables.

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.