问题描述
我刚读过全局常量变量 Q& A,但我发现它们对我的问题不合适。
I've just read all of objective-c global constants variables Q&A but I found them inappropriate to my problem.
我需要一个这样的变量列表:
I need a list of variable like this:
NSString *baseURL = @"http://example.org";
NSString *mediaURL = @"http://example.org/media/";
NSString *loginURL = @"http://example.org/login/";
NSString *postURL = @"http://example.org/post/";
etc.
当然,我不能使用这段代码,因为这是一个非常糟糕的做法如果我需要更改基础网址,我必须更改所有变量。
因为我需要从应用程序的每个类访问这些变量,所以我将它们声明为全局的:
Of course I can't use this code because it's a very bad approach and if I need to change the base url I must change all variables.Since I need these variables to be accessed from every class of the app I declared them as global with this approach:
// Constants.h
extern NSString *const baseURL;
extern NSString *const mediaURL;
extern NSString *const loginURL;
extern NSString *const postURL;
// Constants.m
NSString *const baseURL = @"http://example.org";
NSString *const mediaURL = [NSString stringWithFormat:"%@%@", baseURL, @"/media/"];
NSString *const loginURL = [NSString stringWithFormat:"%@%@", baseURL, @"/login/"];
NSString *const postURL = [NSString stringWithFormat:"%@%@", baseURL, @"/post/"];
但我不能这样做,因为我得到这个错误:
BUT I can't do this because I get this error:
Initializer element is not a compile-time constant
发生这种情况是因为对象在运行时工作。
This happens because objects works at runtime.
现在我的问题是,我希望一劳永逸,什么是好的在网络应用程序中处理这种相当常见的情况的好方法?
Now my question is, once and for all I hope, what is a nice and good way to handle this pretty usual scenario in network apps?
我认为使用类(或单例类)来处理常量变量有点矫枉过正,它也是过于冗长的使用类似于 [MyClass globalVar]
每次我需要它。
I think use a class (or a singleton class) for handle the constants variables is a bit overkill, and it's also too verbose use something like [MyClass globalVar]
every time I need it.
关于它的想法? / p>
Ideas about it?
推荐答案
我知道这是过时的,但我只是使用预处理器宏,并让常量字符串连接处理它。
I know it's old-fashioned but I'd just use preprocessor macros and let constant string concatenation handle it.
#define baseURL @"http://example.org"
#define mediaURL baseURL@"/media/"
这篇关于从其他常量构建一个常量变量列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!