如何#define NSString供全球使用?

mar*_*ada 30 objective-c ios4

我是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)

  • define只是一个宏,因此每次出现宏时,都会创建一个新字符串.const NSString只创建一个字符串引用.我还发现常量更容易跨文件使用,在键的情况下,常量的实际值可以隐藏在实现文件中,因为它的实际值对于实现来说并不重要. (6认同)

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)