我是Objective-C的新手.基本上我想将一组端点URL存储为在我的应用程序中使用的字符串,但我需要一个基于应用程序是否处于DEBUG模式的不同域.我认为使用头文件(Common.h例如)和一些简单的定义可能是有用的,如下所示:
#ifdef DEBUG
#define kAPIEndpointHost @"http://example.dev"
#else
#define kAPIEndpointHost @"http://www.example.com"
#endif
#define kAPIEndpointLatest [kAPIEndpointHost stringByAppendingString:@"/api/latest_content"]
#define kAPIEndpointMostPopular [kAPIEndpointHost stringByAppendingString:@"/api/most_popular"]
Run Code Online (Sandbox Code Playgroud)
显然这不起作用,因为你不能明显地将常量基于另一个常量的值.
这样做的"正确"方法是什么?只有拥有一个返回正确端点值的类方法的适当类才更有意义吗?
编辑:为了清楚,基于主机字符串的"Latest"和"MostPopular" 字符串是我最麻烦的.编译器不喜欢stringByAppendingString#defines 的部分.
cob*_*bal 64
如果您只是连接字符串,则可以使用编译时字符串连接:
#ifdef DEBUG
#define kAPIEndpointHost @"http://example.dev"
#else
#define kAPIEndpointHost @"http://www.example.com"
#endif
#define kAPIEndpointLatest (kAPIEndpointHost @"/api/latest_content")
#define kAPIEndpointMostPopular (kAPIEndpointHost @"/api/most_popular")
Run Code Online (Sandbox Code Playgroud)
Eri*_*ric 19
我不喜欢将#defines用于字符串常量.如果需要全局常量并编译时间连接.我会使用以下内容:
头文件:
extern NSString *const kAPIEndpointHost;
extern NSString *const kAPIEndpointLatestPath;
extern NSString *const kAPIEndpointMostPopularPath;
Run Code Online (Sandbox Code Playgroud)
实施文件:
#ifdef DEBUG
#define API_ENDPOINT_HOST @"http://example.dev"
#else
#define API_ENDPOINT_HOST @"http://www.example.com"
#endif
NSString *const kAPIEndpointHost = API_ENDPOINT_HOST;
NSString *const kAPIEndpointLatestPath = (API_ENDPOINT_HOST @"/api/latest_content");
NSString *const kAPIEndpointMostPopularPath = (API_ENDPOINT_HOST @"/api/most_popular");
Run Code Online (Sandbox Code Playgroud)
Bla*_*rog 11
在您的头文件中:
extern NSString *const kAPIEndpointHost;
extern NSString *const kAPIEndpointLatestPath;
extern NSString *const kAPIEndpointMostPopularPath;
Run Code Online (Sandbox Code Playgroud)
在您的实现文件中:
#ifdef DEBUG
NSString *const kAPIEndpointHost = @"http://example.dev";
#else
NSString *const kAPIEndpointHost = @"http://www.example.com";
#endif
NSString *const kAPIEndpointLatestPath = @"/api/latest_content";
NSString *const kAPIEndpointMostPopularPath = @"/api/most_popular";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38400 次 |
| 最近记录: |