声明依赖于 Objective C 中#defines 的字符串常量的正确方法
我需要声明一堆恒定的 URL,但可能会根据构建配置而有所不同。
现在我拥有的是:
一个 .h 文件声明如下内容:
extern NSString * const MY_URL;
相应的.m文件包含:
NSString * const MY_URL = @"http://myhost/myfolder";
我希望能够根据构建标志更改“myhost”。我的尝试是创建一个定义,例如:
#ifdef MYFLAG
# define HOST @"http://myhost"
#else
# define HOST @"http://myotherhost"
#endif
然后通过将 HOST 附加到字符串的其余部分来创建常量:
NSString * const MY_URL = [HOST stringByAppendingString:@"/myfolder"];
但显然“初始化器元素不是常量”。
所以我的问题是:
我的方法正确吗?如果是这样,你能告诉我正确的做法吗? 也许这不是 Objective C 中应该做的事情?
非常感谢您的宝贵时间!
I need to declare a bunch of URLs that will be constant but may be different depending on the building configuration.
Right now what I have is:
A .h file declaring things like:
extern NSString * const MY_URL;
The corresponding .m file with:
NSString * const MY_URL = @"http://myhost/myfolder";
I would like to be able to change "myhost" depending on building flags. My attempt was to create a define such as:
#ifdef MYFLAG
# define HOST @"http://myhost"
#else
# define HOST @"http://myotherhost"
#endif
And then create the constants by appending the HOST with the rest of the string:
NSString * const MY_URL = [HOST stringByAppendingString:@"/myfolder"];
But apparently "Initializer element is not constant".
So my questions are:
Is my approach correct? If so, can you show me the proper way of doing it?
Maybe this is not the way this kind of things should be done in objective c?
Thanks a lot for your time!
看看这个 Stack Overflow 答案
您不能使用另一个变量的结果来初始化 const,即使该结果是 const。
完成您想要的操作的一种方法是将定义包装在标志中:
编辑 - 疯狂的想法!
好的,所以您不想手动配置一堆网址。这是一个疯狂的想法:创建一个提供所需 URL 的类怎么样?这样,您可以将它们设置在一个地方,并且您的优点是只需将它们转换为网址。例如
然后你可以声明类
是的,这太疯狂了。但通过这种方式,您可以在一个地方控制所有 URL。
Have a look at this Stack Overflow answer
You can't initialise a const with the result of another variable, even if that result is a const.
One way to do what you want is to wrap the definitions in flags:
Edit - Crazy idea!
Okay, so you don't want to have to manually configure a bunch of urls. Here's a crazy idea: How about you create a class that provides the URLs you need? That way, you can set them up in one place, and you have the advantage of only having to translate them into urls in one place. For example
Then you can declare the class
Yes, it's crazy. But this way you can control all your URLs in one place.