tags:

views:

97

answers:

2

I have a define:

hashdefine kPingServerToSeeIfInternetIsOn  "http://10.0.0.8"

then in code I with to use it:

NSString *theURL = [NSString stringWithFormat:@"%@", kPingServerToSeeIfInternetIsOn];

I get an exception.

What's the best way to define the const for the application and use it in a NSString init?

+2  A: 

Create a header file, e.g. MyAppConstants.h. Add the following:

extern NSString * const kPingServerToSeeIfInternetIsOn;

In the definition, e.g. MyAppConstants.m, add:

NSString * const kPingServerToSeeIfInternetIsOn = @"http://10.0.0.8";

In your class implementation, add:

#import "MyAppConstants.h"

You can use the constant as you have done already.

Alex Reynolds
While I strongly agree with using consts rather than defines, I strongly disagree with creating a file like "MyAppConstants.h". This makes code-reuse very hard. Put constants in the files that logically provide them, or at least in the file that uses them. But don't create a central dumping ground for all system constants.
Rob Napier
There is a place for having constants in the same file as the class. But I do find having my constants hinted in only a few header files (organized by larger code function) makes my troubleshooting *much* easier. It's no fun hunting them down or having to refactor a bunch of them from different places. At the very least, develop a consistent and informative naming scheme for your constants and stick to it like glue.
Alex Reynolds
+8  A: 

You've #defined it as a C string.

If you want it as an Objective-C String, you need

#define kPingServerToSeeIfInternetIsOn @"http://10.0.0.8"
Ken