views:

72

answers:

2

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, right?

+1  A: 

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.

tonio
+1  A: 

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).

Michael Aaron Safyan