我刚刚读完全部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.
当然,我不能使用这段代码,因为这是一个非常糟糕的方法,如果我需要更改基本 url,我必须更改所有变量。
由于我需要从应用程序的每个类访问这些变量,因此我使用以下方法将它们声明为全局变量:
// 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我无法执行此操作,因为我收到此错误:
Initializer element is not a compile-time constant
发生这种情况是因为对象在运行时工作。
现在我的问题是,我希望一劳永逸地,有什么好的方法来处理网络应用程序中这种非常常见的情况?
我认为使用类(或单例类)来处理常量变量有点矫枉过正,而且使用类似的东西也太冗长了[MyClass globalVar]
每次我需要它的时候。
关于它的想法?