0

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?

1
  • 1
    Why do you need this done at compile time? What are you trying to accomplish. Commented Nov 23, 2013 at 16:20

2 Answers 2

1

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.

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

2 Comments

I'm just experimenting with code generating capabilities of objective-C. I know that preprocessor is a bad way. But may be there are some other ways for this? Say generate some repeated code auromatically?
You might want to read about associated objects sebastianrehnby.com/blog/2013/01/24/…
1

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.

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.