0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Reid Ellis
  • 3,996
  • 1
  • 21
  • 17

1 Answers1

0

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.

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
  • _"strings should be defined as `copy` properties, not `strong`"_ Really? Why? Can't find any documentation suggesting this. –  Apr 24 '12 at 19:20
  • @QwertyBob simply because `NSString` has a mutable subclass, you never know if you are passed in a Mutable string instead of an immutable one, and the string may change without notice. – Richard J. Ross III Apr 24 '12 at 19:44
  • 1
    This article explains it well (although it uses the old, pre-ARC retain/release nomenclature): http://stackoverflow.com/questions/387959/nsstring-property-copy-or-retain – Reid Ellis Apr 24 '12 at 19:46