Ethan Allen
Ethan Allen

Reputation: 14835

What's the best way to get a value from NSUserDefaults on app load and store it in a global variable?

What's the best way to get a value from NSUserDefaults on app load and store it in a global variable?

I could just hit [[NSUserDefaults standardUserDefaults] objectForKey:@"Theme"] every time I wanted to access the value stored, but it would hit the disk every time and that would be bad (I need the value for UITableView cells). What I'd like to do is store that value from it to a global variable on load, and then use that variable throughout the app.

What's the best way to do this? Obviously I can't make a constant because [[NSUserDefaults standardUserDefaults] objectForKey:@"Theme"] can't be compiled as a constant. How should I make a global variable for this? Is there any way to put it in the main.m or Prefix.pch file? I would hate to have to hit the App Delegate every time throughout my whole app.

Upvotes: 2

Views: 286

Answers (1)

hypercrypt
hypercrypt

Reputation: 15376

"NSUserDefaults caches the information to avoid having to open the user’s defaults database each time you need a default value." - NSUserDefaults Class Reference

However, if you really want to have this 'constant' (it won't be a true constant though) do something like this

*.pch:

extern NSString *themeString;

AppDelegate.m:

NSString *themeString = nil;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // ...
    themeString = [[[NSUserDefaults standardUserDefaults] objectForKey:@"Theme"] copy];
    // ...
}

Upvotes: 3

Related Questions