【发布时间】:2012-04-20 18:17:42
【问题描述】:
我刚刚阅读了所有 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/"];
但是我不能这样做,因为我收到了这个错误:
Initializer element is not a compile-time constant
这是因为对象在运行时工作。
现在我的问题是,我希望一劳永逸地,在网络应用程序中处理这种非常常见的场景的好方法是什么?
我认为使用类(或单例类)来处理常量变量有点矫枉过正,而且每次需要时都使用 [MyClass globalVar] 之类的东西也太冗长了。
有什么想法?
【问题讨论】:
标签: iphone objective-c ios global-variables constants