开发者

How to #define an NSString for global use?

I'm new to Objective-C. Essentially I want to store a set of Endpoint URLs as strings for use in my application, but I need a different domain based on whether the app is in DEBUG mode or not. I thought 开发者_StackOverflow社区it might be useful to use a header file (Common.h for example) with some simple defines like so:

#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"]

Obviously this doesn't work since you can't base a constant on the value of another constant apparently.

What's the "right" way to do this? Would it make more sense just to have a proper class with class methods that return the correct endpoint values?

EDIT: Just to be clear, the "Latest" and "MostPopular" strings that are based on the host string are what I'm having the most trouble with. The compiler doesn't like the stringByAppendingString portion of the #defines.


If you're just concatenating strings, you can use compile time string concatenation:

#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")


I don't like using #defines for string constants. If you want global constants and compile time concatenation. I would use the following:

Header file:

extern NSString *const kAPIEndpointHost;
extern NSString *const kAPIEndpointLatestPath;
extern NSString *const kAPIEndpointMostPopularPath;

Implementation file:

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


In your header file:

extern NSString *const kAPIEndpointHost;
extern NSString *const kAPIEndpointLatestPath;
extern NSString *const kAPIEndpointMostPopularPath;

In your implementation file:

#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";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜