tags:

views:

52

answers:

2
 NSString* const nits = @"nits";
 NSString* const nuts = nits;  // error: "initializer element is not constant"

How is this done?

+1  A: 

I don't know objective-c but I would imagine that by initialising something from a value that is not a literal then you end up with not a constant - regardless of the initial value declaration.

Dan Iveson
+2  A: 

Constant String literals such as your @"nits" are hardcoded into objective-c binary files. String constants such as nits and nuts have to be defined as a constant string literal, as they are hard-coded as well. The assignment nuts = nits does not work because nits is not a constant string literal, even though the variable is constant at runtime.

There are two ways to fix this:

  1. write the string literal @"nits" twice
  2. use a #define

This might look like this:

 #define NitsNutsString @"nits"
 NSString* const nits = NitsNutsString;
 NSString* const nuts = NitsNutsString;

Alternatively you can use #defines only, but these cannot be exported in a header as cleanly as const strings.

Max Seelemann
Do you mean #define?
invariant
right, must have had a single event upset in my brain, fixed it ;)Also feels better now :)
Max Seelemann
you missed one.
JeremyP
but now it should be fixed, tx.
Max Seelemann