18

I'm trying to instanciate a constant NSString by concatanating other NSString instances.

Here is what I'm doing in my implementation file :

static NSString *const MY_CONST = @"TEST";
static NSString *const MY_CONCATENATE_CONST = [NSString stringWithFormat:@"STRING %@", MY_CONST];

It leads to the following compilation error : Initializer element is not constant

I suppose this is because stringWithFormat doesn't return a constant NSString, but since there is no other way to concatenate strings in Obj-C, what am I supposed to do ?

Thanks for your help,

Eric.

3 Answers 3

51

I thought there must be a way to do this but the best I could do was using a #define directive. For example,

// Define the base url as an NSString
#define BASE_URL @"http://www.milhouse.co.uk/"

// Now the derived strings glued by magic
NSString *const kBaseURL    = BASE_URL;
NSString *const kStatusURL  = BASE_URL @"status.html";
NSString *const kBalanceURL = BASE_URL @"balance.html";
1
  • I'm getting duplicate symbol _kActivityLogURL error Apr 5, 2014 at 12:44
4

static const objects value is determined at compile-time so you indeed cannot add any method calls to their initialization. As an alternative you can do the following:

static NSString *const MY_CONST = @"TEST";
static NSString *MY_CONCATENATE_CONST = nil;

if (nil == MY_CONCATENATE_CONST)
   MY_CONCATENATE_CONST = [NSString stringWithFormat:@"STRING %@", MY_CONST];
1

I think you need to step back and think about if the string needs to be defined as a const.

Clearly the string isn't a constant since you are trying to assign a new value to it - and that is not possible since you specifically instructed the compiler to make sure the value wasn't changed by using the const keyword.

If the string resides as a property in a class you could make it a read-only property - i.e. accessor method but no setter method. You would then be able to construct your string as you wish in the class internally while keeping the callers from changing the value.

1
  • 10
    I agree on this, but what if I need to define a constant (an actual one, that will never change) by concatenating other constants ? In Java, this is trivial : private static final String CONST1 = "CONST1"; private static final String CONST2 = "CONST2"; private static final String CONCAT = CONST1 + " " + CONST2; This allows me to have 3 constants, the third one being the concatenation of the two others. Jun 17, 2010 at 9:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.