Mar 25
After yesterday’s elaborate tutorial on how to create a Preferences UI, accessing the preferences from your code is a snap.
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; delayBeforeDialing = [userDefaults floatForKey:@"delayBeforeDialing"];
The key, “delayBeforeDialing” in this example, needs to match the Key value in Root.plist.
There are different accessor methods depending on the type of variable you want to retrieve.
- arrayForKey
- boolForKey
- dataForKey
- dictionaryForKey
- floatForKey
- integerForKey
- objectForKey
- stringArrayForKey
- stringForKey
You don’t have to use a UI for your preferences. If you just want to conveniently store values associated with your application, that you can read back later, you can use the setter methods of NSUserDefaults.
[userDefaults setFloat:delayBeforeDialing forKey:@"delayBeforeDialing"];
Read back the values as above.
September 2nd, 2008 at 13:49
It says the delayBeforeDialing is undeclared for the second line of code you provided.
March 9th, 2009 at 05:31
How To Access Preferences From Your iPhone App…
You’ve been kicked (a good thing) – Trackback from iPhoneKicks.com – iPhone SDK links, community driven…
March 11th, 2009 at 11:43
Hey Gabe,
You just need to declare that variable. Example:
NSString *prefkey = [userDefaults stringForKey:@”prefkey”];
March 11th, 2009 at 11:44
Nick:
Is there some easy way to have a “Settings” button link to our new settings bundle in the iPhone settings app?
March 11th, 2009 at 12:20
@Bryan: Unfortunately there is no way to launch the Settings app from within your own app.
July 21st, 2009 at 23:51
I have entered the code as your instructions above and all i get is an error: “initializer element is not constant”
Any clues?
December 30th, 2009 at 20:50
Just wondering what file do I place the following in
NSString *prefkey = [userDefaults stringForKey:@”prefkey”];
December 31st, 2009 at 10:37
@Russell: You can read preferences from pretty much any file. So place that line of code where you need the value.
February 26th, 2010 at 18:26
Is it possible to change the Iphone’s core preferences with an app?
February 26th, 2010 at 21:39
@nick: No that is not possible.
August 16th, 2011 at 16:43
Hi,
Is that possible to manage settings as switch off the wifi or delete cache and history ?
Or are those what we can call core preferences?
Lyndon
August 17th, 2011 at 07:50
@lyndon: No, you cannot access any system preferences. This method only applies to your own preferences defined by and for your own app.