Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

objective c - How to create constant NSString by concatenating strings in Obj-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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...