在iOS应用程序中存储全局常量的位置? [英] Where to store global constants in an iOS application?
问题描述
我的iOS应用程式中的大部分模型都会查询网页伺服器。我想有一个配置文件存储服务器的基本URL。它将看起来像这样:
// production
pre>
// static NSString * const baseUrl =http: /website.com/
//测试
static NSString * const baseUrl =http://192.168.0.123/
通过注释掉一行或另一行,我可以立即改变模型指向的服务器。我的问题是,在iOS中存储全局常量的最佳做法是什么?在Android编程中,我们有这个内置的字符串资源文件。在任何活动(相当于 UIViewController ),我们可以检索这些字符串常量:
String string = this.getString(R.string.someConstant);
我想知道iOS SDK是否有类似的地方来存储常量。如果不是,Objective-C中的最佳做法是什么?解决方案您也可以执行
#define kBaseURL @http://192.168.0.123/
<常量头文件,例如constants.h
。然后执行#includeconstants.h
这样,您可以根据编译器在服务器之间切换标志,如:
#ifdef DEBUG
#define kBaseURL @http://192.168.0.123/
#else
#define kBaseURL @http://myproductionserver.com/
#endif
Most of the models in my iOS app query a web server. I would like to have a configuration file storing the base URL of the server. It will look something like this:
// production // static NSString* const baseUrl = "http://website.com/" // testing static NSString* const baseUrl = "http://192.168.0.123/"
By commenting out one line or the other, I can instantly change which server my models point to. My question is, what's the best practice for storing global constants in iOS? In Android programming, we have this built-in strings resource file. In any Activity (the equivalent of a UIViewController), we can retrieve those string constants with:
String string = this.getString(R.string.someConstant);
I was wondering if the iOS SDK has an analogous place to store constants. If not, what is the best practice in Objective-C to do so?
解决方案You could also do a
#define kBaseURL @"http://192.168.0.123/"
in a "constants" header file, say
constants.h
. Then do#include "constants.h"
at the top of every file where you need this constant.
This way, you can switch between servers depending on compiler flags, as in:
#ifdef DEBUG #define kBaseURL @"http://192.168.0.123/" #else #define kBaseURL @"http://myproductionserver.com/" #endif
这篇关于在iOS应用程序中存储全局常量的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!