ArtS
ArtS

Reputation: 2012

How to deal with arguments in macro names in Objective-C?

The idea is to setup several fixed CGPoint values with macros, and read them in code flexibly (randomly or with provided integer value)

I have a header file defining several CGPoints value like this:

#define kSpawnPoint1 {550,20}
#define kSpawnPoint2 {550,80}
#define kSpawnPoint3 {200,175}

I'm generating a random integer in my code between 1 to 3, and plan to read the CGPoint value in the macro according to the integer value. But don't know how to do it. After learning other tutorials about preprocessors, I write my code like following.

#define kSpawnPoint1 {550,20}
#define kSpawnPoint2 {550,80}
#define kSpawnPoint3 {200,175}
#define kSpawnPoint(x) kSpawnPoint##x

in the m file:

int tempInt = 1;
CGPoint tempSpawnPoint = kSpawnPoint(temInt);

However it doesn't work.(with warning: undeclared identifier 'kSpawnPointspawnPoint') How can I make this right? And is it the right way to pre-define several CGPoint? I think I must use the preprocessor to achieve this considering future multi-screen resolution support would be easier to implement in macro too, and my kSpawnPoints would not be the same with different screen resolution.

Upvotes: 1

Views: 182

Answers (1)

jscs
jscs

Reputation: 64002

Macros only operate on text, not the values of variables. When you write kSpawnPoint(an_int), the preprocessor takes the literal string "an_int" and then pastes it, so you end up with kSpawnPointan_int. Thus, you would have to put a literal number as the argument in order to end up with one of your points: kSpawnPoint(1) -> kSpawnPoint1 -> {550, 20}

To choose randomly among your macros, you will have to put them into a structure that will exist at runtime, like an array or a switch statement.

Upvotes: 1

Related Questions