从其他常量构建常量变量列表

Fre*_*ins 5 iphone constants global-variables objective-c ios

我刚刚阅读了所有objective-c全局常量变量问答,但我发现它们不适合我的问题.

我需要一个像这样的变量列表:

NSString *baseURL = @"http://example.org";
NSString *mediaURL = @"http://example.org/media/";
NSString *loginURL = @"http://example.org/login/";
NSString *postURL = @"http://example.org/post/";
etc.
Run Code Online (Sandbox Code Playgroud)

当然我不能使用这段代码,因为这是一个非常糟糕的方法,如果我需要更改基本URL,我必须更改所有变量.因为我需要从应用程序的每个类访问这些变量,所以我使用这种方法将它们声明为全局:

// Constants.h
extern NSString *const baseURL;
extern NSString *const mediaURL;
extern NSString *const loginURL;
extern NSString *const postURL;
Run Code Online (Sandbox Code Playgroud)


// 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/"];
Run Code Online (Sandbox Code Playgroud)

我不能这样做,因为我收到此错误:

Initializer element is not a compile-time constant
Run Code Online (Sandbox Code Playgroud)

这是因为对象在运行时工作.

现在我的问题是,一劳永逸,我希望,在网络应用程序中处理这种非常常见的场景有什么好方法?

我认为使用一个类(或一个单独的类)来处理常量变量有点矫枉过正,而且[MyClass globalVar]每次我需要的时候也会使用类似的东西.

关于它的想法?

Phi*_*lls 4

我知道它很老式,但我只是使用预处理器宏并让常量字符串连接来处理它。

#define baseURL @"http://example.org"
#define mediaURL baseURL@"/media/"
Run Code Online (Sandbox Code Playgroud)