0

I have a collection of static NSString consts in one of my header files that I would like to utilize in a new static NSArray (or NSString[]) but am running into the following error

Initializer Element is not a compile-time constant

My strings and array are set up as follows:

static NSString * const SOMEVAL = @"val";
static NSString * const SOMEKEY = @"key";

static NSString *KEYLIST[] = { SOMEVAL, SOMEKEY };

Is it possible to get this static array to compile in this manner or will the previously declared NSStrings always show up as non-compile-time constants?

Maixy
  • 1,151
  • 2
  • 12
  • 27

3 Answers3

2

The compiler will never treat objects as "compile-time constants"; you will have to do one of two workarounds.

You can use preprocessor definitions for the strings:

#define KEY @"key"
#define VAL @"val"

static NSString * const key = KEY;
static NSString * const val = VAL;

static NSString * keyVal[] = { KEY, VAL };

Or you can initialize the array in a function or method which is guaranteed to be called before you need the array. The constructor function attribute is one option:

static NSString * keyVal[2];

__attribute__((constructor))
void setKeyVal(void)
{
    keyVal[0] = key;
    keyVal[1] = val;
}

The +initialize method of a closely-related class is another.

Community
  • 1
  • 1
jscs
  • 63,694
  • 13
  • 151
  • 195
0

You shouldn't use static in a header file. In the header declare:

extern NSString * const SOMEVAL;
extern NSString * const SOMEKEY;

extern NSString *KEYLIST[];

and then in a source file define:

NSString * const SOMEVAL = @"val";
NSString * const SOMEKEY = @"key";

NSString *KEYLIST[] = { SOMEVAL, SOMEKEY };
combinatorial
  • 9,132
  • 4
  • 40
  • 58
0

If you're willing to rely on the compiler combining identical string constants (a pretty safe bet), you can do this instead:

#define SOMEVAL @"val"
#define SOMEKEY @"key"

static NSString *KEYLIST[] = { SOMEVAL, SOMEKEY };
rob mayoff
  • 375,296
  • 67
  • 796
  • 848