Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create constant NSString by concatenating strings in Obj-C?

Tags:

objective-c

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.

like image 557
Eric MORAND Avatar asked Jun 17 '10 08:06

Eric MORAND


People also ask

How to append string to NSString in Objective C?

The format specifier “%@” is used to insert string values. The example below uses a combination of whitespace and %@ format specifiers to append two strings to string1: NSString * string3 = [string1 stringByAppendingFormat:@" %@ %@", string2, @"A third string.

How do you concatenate in Objective C?

You use it with @"%@%@" to concatenate two strings, @"%@%@%@" to concatenate three strings, but you can put any extra characters inside, print numbers, reorder parameters if you like and so on. The format string can be localised, making it ten times more powerful. String concatenation is for beginners.

How do I get substring in Objective C?

NSString *needle = [haystack componentsSeparatedByString:@":"][1]; This one creates three temporary strings and an array while splitting. All snippets assume that what's searched for is actually contained in the string. Ky.


2 Answers

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";
like image 183
Patrick Avatar answered Oct 01 '22 15:10

Patrick


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];
like image 27
Vladimir Avatar answered Oct 01 '22 14:10

Vladimir