It is my experience that, when developing a J2ME application, excessive String creation is often the leading cause of memory “leaks”. There is always that step during the development cycle where you go back over all your code and refactor out any strings that should be defined as constants. This is no less true of Objective-C and iPhone development. What was not obvious to me initially, was what the correct method was to accomplish the equivalent this line of Java in Objective-C:
public static final String HTTP_METHOD_POST = "Post";
Definitely Don’t Use #define Macros
My first assumption was to use the #define macro construct to define the string which would look something like this a header (*.h) file …
#define HTTP_METHOD_POST @"POST"
… and would be used in the implementation file something like this …
[urlRequest setHTTPMethod: HTTP_METHOD_POST];
Although this would work fine, it doesn’t solve the main issue of reducing the number of instances of HTTP_METHOD_POST being created. Macros replace before the code is compiled, so the end result is effectively:
[urlRequest setHTTPMethod: @"POST"];
… which is right back where we started.
Public String Constants Using ‘extern’
The correct way to define a string constant is to define the string as an
extern NSString *const. Here is how you would declare the constant in your header file:
extern NSString *const HTTP_METHOD_POST;
… and in the implemenation file (*.m) …
NSString *const HTTP_METHOD_POST = @"POST";
In my code I have started to always define a class that is specifically designed hold all my application’s global constants. To use the constants, you need only include the header file of the constants file.
Private String Constants Using ‘static’ (Optional)
Not all string constants need to be accessible publicly. That is to say, they are only ever used by a single class. For these classes. Our example above might be better declared in Java as:
private static final String HTTP_METHOD_POST = "POST";
… in Objective-C you can handle this by declaring the string as a
static variable in your implementation file (*.m) like this:
1 2 3 4 5
static NSString *const HTTP_METHOD_POST = @"POST"; @implementation // method and stuff here @end
When declaring a variable using the
static modifier, it is not necessary to define anything in the header; which makes sense because it is a private constant.