Set settings-variable from code?

Discussion in 'iOS Programming' started by Danneman101, May 19, 2009.

  1. Danneman101 macrumors 6502

    Aug 14, 2008
    I know I can get the value of a variable in the settings with this code:

    NSString *str_Value = [[NSUserDefaults standardUserDefaults] stringForKey:@"settings_Value1"];	
    But is it also possible to set the value from within the code? And if so, how?
  2. BlackWolf macrumors regular

    Apr 9, 2009
  3. Danneman101 thread starter macrumors 6502

    Aug 14, 2008
    Lol, yeah :)

    But what about strings? The reference only suggests setting-functions for bool, float, int and object...
  4. Danneman101 thread starter macrumors 6502

    Aug 14, 2008
    Apparently, you can use the object-method (thanks smasher):

    [[NSUserDefaults standardUserDefaults] setObject: @"hiMom"  forKey: @"settings_Value1"]];
    So if I understand the NSUserDefaults-class correctly, I can create settings that wont even appear in the settings-pane that the user has access to? Or is there a "NSSystemDefaults"-class or something that takes care of that?
  5. dejo Moderator


    Staff Member

    Sep 2, 2004
    The Centennial State
    userDefaults don't appear in the Settting app unless you've define them as such via a Settings Bundle.

    P.S. An NSString is a serialized subclass of NSObject. Any serialized object can be stored in NSUserDefaults.
  6. Danneman101 thread starter macrumors 6502

    Aug 14, 2008
    Thats great - I was thinking I had to save the settings I didnt want to expose to the user in a separate file, but this way is much handier.

    Ive only created NSUserDefaults using the Settings.bundle (in the xml-editor), so Im not sure how to instantiate a NSUserDefault-object without it.

    I know the syntax for instantiating is:

    // Instantiate NSUsersDefaults:
    NSUserDefaults *myUserDefaults = [NSUserDefaults standardUserDefaults];
    // And the rest - getting and setting - we've already covered:
    // Set:
    [myUserDefaults setObject:@"felix" forKey:@"Username"];
    // Get:
    [[NSUserDefaults standardUserDefaults] stringForKey:@"Username"];
    But where do I put the instantiation-code? Do I put it in the Delegate.h/m-files like this:

    // myDelegate.h
    // ----------------
    @interface myDelegate : NSObject <UIApplicationDelegate, NSUserDefaults>
      NSUserDefaults *myUserDefaults = [NSUserDefaults standardUserDefaults];
    // myDelegate.m
    // ----------------
    @synthesize myUserDefaults;
    But how do I go about setting the default-values for them? If I do that in the delegate-code each time the app starts, wouldnt I overwrite the settings from the last session with my initialization of the defaults? This is a bit onfusing..
  7. ghayenga macrumors regular

    Jun 18, 2008
    [[NSUserDefaults standardUserDefaults] registerDefaults:myDefaultsDictionary];

Share This Page