开发者

Can a macro also generate a method name?

Is it generally valid that a macro is used to create a method name? I mean...actually it's just simple text replacement before the compiler actually runs, righ开发者_C百科t?


Yes, it is valid; macro expansion occurs before the compiler even reads the code. The main limitation is that one cannot embed a preprocessor directive within a preprocessor directive. So, for example:

// This is ok:
#define PREFIX(X) this_name_is_prefixed_ ## X
// ...
- (void) PREFIX(doSomething):id;
// ...

// But this isn't:
#define IMPORT(X) #import X
IMPORT(<Foundation/Foundation.h>) // <= Don't expect this to work

With the exception of the "#import" directive, Objective-C's preprocessor is basically the same as the C preprocessor. (The "#import" is like "#include", except that #import implies include only once, so preprocessor guards are not required for headers that are included only with #import).


There is nothing that prevents that. It is even commonly used (though I don't know for the iphone), for instance, in device drivers implementation. In that case, macros are used to generate boilerplate code, and for this boilerplate to communicate with your code, you have to either guess the correct function names (not advised), or use generating macros, for example USB_ATTACH(uthum) to generate the signature of the attach method for the uthum driver.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜