tagyro
tagyro

Reputation: 1679

Convert variable name to string

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).

Upvotes: 2

Views: 2594

Answers (3)

tagyro
tagyro

Reputation: 1679

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.

Upvotes: 5

Yuji
Yuji

Reputation: 34185

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);

Upvotes: 1

Tom Wetmore
Tom Wetmore

Reputation: 233

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.

Upvotes: 0

Related Questions