开发者

How to make a macro which gives back a string into the source code?

Example: I want to do this:

METHODNAME(5) {
    // do something 
}

which results in:

- (void)animationStep5 {
    // do something 
}

Is there any way to do this? Basically, what I need is a way to generate a real source code string before the program is compiled, so the compiler does see - (void)animat开发者_开发百科ionStep5...

Or maybe there's something different than a macro, which can help here to auto-generate method names (not at run-time)?


As was already answered here, the objective-C preprocessor is very close to the C one.

You should have a look at the examples posted there, and have a look at C proprocessor. You will simply have to use the ## syntax of the preprocessor, to concatenate the method name, and the number you want.


You can use the concatenation operator

#define METHODNAME(i) -(void)animationStep##i

you can call it like

METHODNAME(5){}

This expands to -(void)animationStep5{}


Assuming the objective-c preprocessor behaves the same as the standard C one, you can use something like:

#define PASTE(a, b) a##b
#define METHODNAME(n) PASTE(animationStep,n)

to join the required bits together. This means that

METHODNAME(5)

gets translated to

animationStep5

(you may need to add the "void" from your question to the macro definitino depending on exactly what it is you need to do).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜