Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make NSString macro?

How to make a macro that represents a constant NSString value? I'm getting "Multi-character character constant" and "Character constant too long for its type" warnings when defining in Xcode 4:

#define LEVELTYPEGLASS @"Glass"

Do I need to escape something?

like image 791
Centurion Avatar asked Oct 11 '22 09:10

Centurion


2 Answers

Avoid using defines for string constants. Define as an extern in the header file like this:

extern NSString * const MYLevelTypeGlass;

And them implement in any implementation file:

NSString * const MYLevelTypeGlass = @"Glass";

This gives a few more characters to type, but adds allot of benefits like better typing for Xcode, guaranteed object identity (no duplicate strings). This is how Apple do it, if its good enough for them, it should be good for you.

like image 165
PeyloW Avatar answered Oct 18 '22 09:10

PeyloW


The solution suggested by PeyloW is great. But I just want to note that I got the solution working after I have added #import "Foundation/Foundation.h" to header file. So the header file Constants.h should look like:

#import "Foundation/Foundation.h"

extern NSString * const LEVELTYPEGLASS; 
#define IMAGECOUNT 5
...

Then, implementation file looks like:

#import "Constants.h"

NSString * const LEVELTYPEGLASS = @"Glass";

And if you need to include that into whole project you need to import that in -Prefix.pch file:

#import "Constants.h"

In that case, all the macro definitions resides in Constants.h header file, and some NSString constants resides in Constants.m implementation file. Again, thanks to PeyloW :)

like image 42
Centurion Avatar answered Oct 18 '22 10:10

Centurion