我的 iOS 应用程序中的大多数模型都查询 Web 服务器。我想要一个配置文件来存储服务器的基本 URL。它看起来像这样:
// production
// static NSString* const baseUrl = "http://website.example/"
// testing
static NSString* const baseUrl = "http://192.168.0.123/"
通过注释掉一行或另一行,我可以立即更改我的模型指向的服务器。我的问题是,在 iOS 中存储全局常量的最佳做法是什么?在Android编程中,我们有这个内置的strings resource file .在任何 Activity (相当于 UIViewController ),我们可以通过以下方式检索这些字符串常量:
String string = this.getString(R.string.someConstant);
我想知道 iOS SDK 是否有类似的地方来存储常量。如果不是,那么在 Objective-C 中这样做的最佳实践是什么?
最佳答案
好吧,您希望声明对它相关的接口(interface)是本地的——应用程序范围的常量文件不是一件好事。
同样,最好简单地声明一个 extern NSString* const
符号,而不是使用 #define
:
SomeFile.h
extern NSString* const MONAppsBaseUrl;
SomeFile.m
#import "SomeFile.h"
#ifdef DEBUG
NSString* const MONAppsBaseUrl = @"http://192.168.0.123/";
#else
NSString* const MONAppsBaseUrl = @"http://website.example/";
#endif
除了省略了与 C++ 兼容的 Extern 声明之外,这是您通常会在 Apple 的 Obj-C 框架中看到的。
如果该常量只需要对一个文件或函数可见,那么 *.m
中的 static NSString* const baseUrl
就很好。
https://stackoverflow.com/questions/7116177/
相关文章:
objective-c - 最佳实践 - 您自己的项目/应用程序的 NSError 域和代码
ios - Xcode 9 中的 "This function declaration is not
objective-c - 从 iOS 上的 UIView 将图像保存到应用程序文档文件夹
objective-c - 如何在 Objective-C 中复制对象
ios - Xcode MyProjectName-Bridging-Header.h 不存在
objective-c - 警告 : "format not a string literal an