I am accessing to a a object stored in NSUserDefaults by using a key string from several places in my project. To avoid a mistake when typing a key string i would like to set in global. Is it possible ??
[[NSUserDefaults standardUserDefaults] objectForKey:@"UD_GPS_LAST_UPDATE"];
There are different ways to do that. Two common methods is to use a global NSString constant or a preprocessor #define directive.
A popular approach is to use a global variable. You need to add it to some file. It could be an existing file or a separate file. Make sure that it's outside the @implementation section if it exists. It could look something like this:
NSString *const MyStringConstantIdentifier = @"UD_GPS_LAST_UPDATE";
Then add the same identifier with the extern attribute to a header file which you include in all source files where you want to use the string constant.
extern NSString *const MyStringConstantIdentifier;
Now MyStringConstantIdentifier will refer to the same string in all places where it's used.
[[NSUserDefaults standardUserDefaults] objectForKey:MyStringConstantIdentifier];
Another approach is to use a preprocessor #define directive in a header file. Make sure that you include the header file in all source files where you want to use the identifier.
#define MyStringConstantIdentifier @"UD_GPS_LAST_UPDATE"
Now when you include that header file MyStringConstantIdentifier will be available as a shortcut for writing @"UD_GPS_LAST_UPDATE". This will however put the burden on the preprocessor rahter than the compiler. The difference from using a global variable is that when you use
[[NSUserDefaults standardUserDefaults] objectForKey:MyStringConstantIdentifier];
the preprocessor will actually substitute MyStringConstantIdentifier with @"UD_GPS_LAST_UPDATE" so that the code that the compiler processes looks like this:
[[NSUserDefaults standardUserDefaults] objectForKey:@"UD_GPS_LAST_UPDATE"];
Where this can be a problem is if parts of your code ever moves into a library. Because preprocessing happens at (actually just before depending on how you look at it) compile time the substitution will replace the constant with the string at all places where it is used. Let's say that this is defined in a library. Whenever the string is changed in the library any application which uses it will have to be recompiled.
Yes it is possible.
Indeed this is the best way to use all the constant strings.
You can create a GlobalConstantsAndKeys.h file with below and others
#define kUDGpsLastUpdate @"UD_GPS_LAST_UPDATE"
and then use it throughout your project.
[[NSUserDefaults standardUserDefaults] objectForKey:kUDGpsLastUpdate];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With