Reid Ellis Reid Ellis - 4 months ago 8
Objective-C Question

Preprocessor doesn't allow ":" in token in macro to define property

I've created a macro to define a string property

#define STRING_PREF(NAME) \
@property (nonatomic, strong, getter=NAME, setter=set_##NAME##:) NSString * NAME;


I try using it thusly:

STRING_PREF(username)


but end up with the following error:

error: pasting formed 'set_username:', an invalid preprocessing token
STRING_PREF(username)
^
foo.h:16:62: note: expanded from macro 'STRING_PREF'
@property (nonatomic, strong, getter=NAME, setter=set_##NAME##:) NSString * NAME;
^
1 error generated.


Is it not possible to generate selector names with the preprocessor?

Answer

Just don't paste the :, like this:

#define STRING_PREF(NAME) @property (nonatomic, copy, getter=NAME, setter=set_##NAME:) NSString *NAME;

Also note that strings should be defined as copy properties, not strong.