Since I made this answer to a question marked as a dupe, I'll also answer it here
Sure, you can use defines OR you can use NSString constants. It's really a matter of preference ... I have however seen both a #define
and an NSString const * const
being used before. Defines are easier, and you're probably not going to save that much memory by having constants instead of individual immutable instances of NSString
all over the place.
Some advice is to think about how you export the NSString
constants. You'll probably want EXTERN_PRIVATE
instead of EXTERN
, but my sample code will allow all clients of your header to read the string constants you've declared therein.
What you can do:
- Create a new .m/.c file with a header in Xcode
- In the .m/.c file, declare and initialise your constants
- Export the constant as necessary so other compilation units can access it
constants.h
#ifndef constants_h
#define constants_h
// Export the symbol to clients of the static object (library)
#define EXTERN extern __attribute__((visibility("default")))
// Export the symbol, but make it available only within the static object
#define EXTERN_PRIVATE extern __attribute__((visibility("hidden")))
// Make the class symbol available to clients
#define EXTERN_CLASS __attribute__((visibility("default")))
// Hide the class symbol from clients
#define EXTERN_CLASS_PRIVATE __attribute__((visibility("hidden")))
#define INLINE static inline
#import <Foundation/Foundation.h>
EXTERN NSString const * _Nonnull const devBaseUrl;
#endif /* constants_h */
constants.m
#include "constants.h"
NSString const * _Nonnull const devBaseUrl = @"http://127.0.0.1:8000/";
main.m
#import <Foundation/Foundation.h>
#import "constants.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSLog(@"Constant value: %@", devBaseUrl);
// Prints: Constant value: http://127.0.0.1:8000/
}
return 0;
}