Reputation: 8556
I want to define a macro or some other way I can generate similar variable declarations in compile-time. E.g. I want to declare 50 NSString
variables like so : #define VAR_GENERATOR (var_name, var_content) NSString* var_name = @"var_content"
and do it in a for loop:
for(NSString* string in [stringArray count])
{
NSString* var_name = [NSString stringWithFormat: @"string%d", iteration];
VAR_GENERATOR (var_name, string);
iteration++;
}
Let's say [stringArray count]
== 50 so I want to have 50 NSString
variables declarations like so: NSString* string1 = @"first string from array"
and so on...
So are there some preprocessor ways I can achieve this? Or may be there are some other more elegant and flexible compile-time metaprogramming tools in Objective-C?
Upvotes: 0
Views: 216
Reputation: 3274
What you want to do can't be done using compile-time constructs, for a number of reasons;
The fundamental reason is that the content of var_name
is unknown at compile time, so it is impossible for the compiler to know what the variable should even be named. But even if that was the case, what about variable name collisions ? What would be the stack layout if the compiler allowed this, given that the number of local variables is unknown ?
And allow me to add that even if you were able to do that, then your variable would be declared in the local scope, and would not be accessible outside of your for
loop.
In your place, I'd try to get back to what you are truly wanting to accomplish, and ponder if runtime constructs are necessary.
If the answer is yes, (are you trying to build an interpreter for some language ?), then we got tools to map arbitrary names to values, such as NSMutableDictionnary
or std::map
.
TL;DR : NO, maybe you can expand a bit on what you are trying to accomplish.
Upvotes: 1
Reputation: 131481
In a word, no.
What you posted is RUNTIME code, not compile-time code.
If you want to create an ordered list of strings, use a mutable array. That's what it's for.
Upvotes: 1