user88975
user88975

Reputation: 1648

Unable to access userdefaults

I have created a preference pane for my app. I am storing some basic settings into userdefaults using preference pane. I am not able to access these settings values from the application.

Am saving settings to user defaults as mentioned below:

NSString *fooBar = @"settings_value";
NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
[userDef setObject:fooBar forKey:@"app_setting"];
[userDef synchronize];

Now when I access it from the app as :

NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
NSString *svcEnv = [userDef objectForKey:@"app_setting"];

I get a nil value. But when accessed from the preference pane project I will get the settings values but not in the application.

How can I retrieve settings value in the application ?

Upvotes: 0

Views: 99

Answers (2)

geowar
geowar

Reputation: 4447

[NSUserDefaults standardUserDefaults] returns the defaults for the current application which in the case of a preference pane is the System Preferences application. Instead you need to use the preferences for the domain that has the bundle identifier for the bundle that contains the class of your preference pane:

NSUserDefaults *suds = [NSUserDefaults standardUserDefaults];
NSString * bundleID = [[NSBundle bundleForClass:[self class]] bundleIdentifier];

NSMutableDictionary *prefs = [[suds persistentDomainForName:bundleID] mutableCopy];

To save them back use:

[suds setPersistentDomain:prefs forName:bundleID];
[sud synchronize];

Upvotes: 1

Flexicoder
Flexicoder

Reputation: 8511

You should be using stringForKey:

NSString *svcEnv = [userDef stringForKey:@"app_setting"];

Upvotes: 0

Related Questions