How to declare and use NSString global constants

ios, objective-c

Solution

First, you should go for a real extern C symbol -- not a macro. this is done like so:

SomeFile.h

extern NSString *const MONConstantString;

SomeFile.m

NSString *const MONConstantString = @"MONConstantString";

note that if you use a mix of ObjC and ObjC++, you will need to specify `extern "C"` for C++ TUs -- that's why you will see a `#define`d export which varies by language.

Then, you will want to put the constant near the interfaces it relates to. Taking your example as a lead, you might want a set of interfaces or declarations for your app's preferences. In that case, you might add the declaration to `MONAppsPreferences` header:

MONAppsPreferences.h

extern NSString *const MONApps_Pref_ReminderSwitch;

MONAppsPreferences.m

NSString *const MONApps_Pref_ReminderSwitch = @"MONApps_Pref_ReminderSwitch";

In use:

#import "MONAppsPreferences.h"
...
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:MONApps_Pref_ReminderSwitch];

Problem

Possible Duplicate: Constants in Objective C I store some app settings in NSUserDefaults. NSStrings are used as keys. The problem is I need to access these settings throughout the app using those NSString keys. There is a chance that I mistype such string key when accessing in some part of the app. Throughout the app, I have such statements ``` [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"ReminderSwitch"]; BOOL shouldRemind = [[NSUserDefaults standardUserDefaults] boolForKey:@"ReminderSwitch"]; ``` How and where can I declare a global NSString constant which I can access throughout the app. I will then be able to use that constant without worrying about mistyping those string keys.

Original source

Related problems