在 iOS 应用程序中在哪里存储全局常量? [英] Where to store global constants in an iOS application?

查看:33
本文介绍了在 iOS 应用程序中在哪里存储全局常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 iOS 应用程序中的大多数模型都会查询网络服务器.我想要一个存储服务器基本 URL 的配置文件.它看起来像这样:

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/"

通过注释掉一行或另一行,我可以立即更改我的模型指向的服务器.我的问题是,在 iOS 中存储全局常量的最佳实践是什么?在 Android 编程中,我们有这个内置的 strings 资源文件.在任何 Activity(相当于 UIViewController),我们可以使用以下命令检索这些字符串常量:

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);

我想知道 iOS SDK 是否有类似的地方来存储常量.如果不是,那么在 Objective-C 中这样做的最佳实践是什么?

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?

推荐答案

你也可以做一个

#define kBaseURL @"http://192.168.0.123/"

在constants"头文件中,说constants.h.然后做

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆