correct way of declaring string constants that depend on #defines in objective c
I need to declare a bunch of URLs that will be constant but may be different depending on the building configuration.
Right now what I have is:
A .h file declaring things like:
extern NSString * const MY_URL;
The corresponding .m file with:
NSString * const MY_URL = @"http://myhost/myfolder";
I would like to be able to change "myhost" depending on building flags. My attempt was to create a define such as:
#ifdef MYFLAG
# define HOST @"http://myhost"
#else
# define HOST @"http://myotherhost"
#endif
And then create the constants by appending the HOST with the rest of the string:
NSString * const MY_URL = [HOST stringByAppendingString:@"/myfolder"];
But apparently "Initializer element is not constant".
So my questions are:
Is my approach correct? If so, can you show me the proper way of doing it? Maybe this is not the way this kind of things should be done in objectiv开发者_如何学Goe c?
Thanks a lot for your time!
Have a look at this Stack Overflow answer
You can't initialise a const with the result of another variable, even if that result is a const.
One way to do what you want is to wrap the definitions in flags:
#ifdef MYFLAG
# NSString * const MY_URL = @"http://myhost/myfolder";
#else
# NSString * const MY_URL = @"http://myotherhost/myfolder";
#endif
Edit - Crazy idea!
Okay, so you don't want to have to manually configure a bunch of urls. Here's a crazy idea: How about you create a class that provides the URLs you need? That way, you can set them up in one place, and you have the advantage of only having to translate them into urls in one place. For example
//HostURLs.h
#import <Cocoa/Cocoa.h>
@interface HostURLs : NSObject {
@private
NSString *baseURLString;
NSString *myURLString1;
NSString *myURLString2;
}
@property (nonatomic, readonly) NSURL *myURL1;
@property (nonatomic, readonly) NSURL *myURL2;
@end
Then you can declare the class
//HostURLs.m
#import "hostURLs.h"
@implementation HostURLs
- (id)init {
// You might want to set this up as as Singleton.
if (!(self = [super init])) {
return nil; // Bail!
}
#ifdef MYFLAG
baseURLString = @"http://myhost/";
#else
baseURLString = @"http://myotherhost/";
#endif
myURLString1 = @"myURL1";
myURLString2 = @"myURL2";
return self;
}
- (NSURL *)myURL1 {
NSString *urlString = [baseURLString stringByAppendingString:myURLString1];
return [NSURL urlWithString:urlString];
}
- (NSURL *)myURL2 {
NSString *urlString = [baseURLString stringByAppendingString:myURLString2];
return [NSURL urlWithString:urlString];
}
@end
Yes, it's crazy. But this way you can control all your URLs in one place.
精彩评论