0

Is it okay to call this?

[[[NSUserDefaults standardUserDefaults] objectForKey:@"searchEnginesOrder"] addObject:@"eBay"];

I have a UITableView whose cells I want to load directly from the defaults, and I also want to modify those defaults. I'm wondering if the above line actually has any effect (when I NSLog the default's array searchEngineOrder it's null, I'm wondering if it's because the above code isn't actually adding to the defaults.

Wain
  • 118,658
  • 15
  • 128
  • 151
user3266395
  • 85
  • 1
  • 8
  • Nope. Any object you get back from defaults is immutable. What you can do is get a mutable copy, append and save again. – Alladinian Feb 06 '14 at 10:34

2 Answers2

3

Generally speaking, that line of code would crash. User defaults returns immutable objects so calling addObject: will throw an exception.

You also shouldn't rely on changes made to returned objects being backed into the data store - this isn't user defaults specific, it goes for any API which doesn't document it as supported.

You should be separating your logic between your working data and your stored data with defined modifications and save points. Ensure that you mutable copy the data you extract from user defaults. You should also use registerDefaults: to setup initial values so you don't need to check for existence.

Wain
  • 118,658
  • 15
  • 128
  • 151
  • It doesn't crash the program, but as far as I can see doesn't have any effect. Also, is it ok to do something like the following: 'dict = [[[NSUserDefaults standardUserDefaults] objectForKey@"searchEnginesOrder"] mutableCopy]'? Thanks so far. – user3266395 Feb 06 '14 at 10:36
  • Not crashing probably means that you never set a value into defaults. Yes, you can mutable copy like that. – Wain Feb 06 '14 at 10:39
  • 1
    It's not crashing because in Objective C you can send any messages to nil, they just do nothing and return 0 (nil, NULL). As you haven't stored any object for @"searchEnginesOrder" key, your code is essentially `[nil addObject:@"eBay"]`. – Kreiri Feb 06 '14 at 10:46
0

NSUserDefaults returns immutable objects. You have to create mutable copies in order to edit the values.

NSMutableDictionary *subSettings;

subSettings = [[[NSUserDefaults standardUserDefaults]
                objectForKey:YOUR_SUBMAP_KEY] mutableCopy];
[subSettings setObject:YOUR_NEW_VALUE forKey:YOUR_VALUE_KEY];

[[NSUserDefaults standardUserDefaults]
  setObject:subSettings forKey:YOUR_SUBMAP_KEY];

[subSettings release];
lupz
  • 3,620
  • 2
  • 27
  • 43