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.

written by Nick \\ tags:

12 Responses to “How To Access Preferences From Your iPhone App”

  1. Gabe Jacobs Says:

    It says the delayBeforeDialing is undeclared for the second line of code you provided.

  2. iPhoneKicks.com Says:

    How To Access Preferences From Your iPhone App…

    You’ve been kicked (a good thing) – Trackback from iPhoneKicks.com – iPhone SDK links, community driven…

  3. Bryan Says:

    Hey Gabe,
    You just need to declare that variable. Example:
    NSString *prefkey = [userDefaults stringForKey:@”prefkey”];

  4. Bryan Says:

    Nick:
    Is there some easy way to have a “Settings” button link to our new settings bundle in the iPhone settings app?

  5. Nick Says:

    @Bryan: Unfortunately there is no way to launch the Settings app from within your own app.

  6. Doug Says:

    I have entered the code as your instructions above and all i get is an error: “initializer element is not constant”

    Any clues?

  7. Russell Says:

    Just wondering what file do I place the following in
    NSString *prefkey = [userDefaults stringForKey:@”prefkey”];

  8. Nick Says:

    @Russell: You can read preferences from pretty much any file. So place that line of code where you need the value.

  9. nick N Says:

    Is it possible to change the Iphone’s core preferences with an app?

  10. Nick Says:

    @nick: No that is not possible.

  11. lyndon Says:

    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

  12. Nick Says:

    @lyndon: No, you cannot access any system preferences. This method only applies to your own preferences defined by and for your own app.

Leave a Reply