1

I am trying to remove an object from a dictionary which is in userdefaults.

NSMutableDictionary *userDefaults = (NSMutableDictionary*)[[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
[userDefaults removeObjectForKey:@"XYZ"];

The above code removes the whole dictionary.

XYZ is a NSMutuableDictionary. I want to remove an object with key "Password" from XYZ.

nicael
  • 18,550
  • 13
  • 57
  • 90
Amon
  • 99
  • 1
  • 9

2 Answers2

3
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *dict = [[defaults objectForKey:@"XYZ"] mutableCopy];
[dict removeObjectForKey:@"Password"];
[defaults setObject:dict forKey:@"XYZ"];
Wyetro
  • 8,439
  • 9
  • 46
  • 64
brl214
  • 527
  • 1
  • 6
  • 16
  • i tried this.but am getting an error "mutating method send to inmutable object" – Amon Jun 30 '16 at 14:09
  • 3
    NSUserDefaults will return an immutable NSDictionary, make a mutable copy of it. `[[defaults objectForKey:@"XYZ"] mutableCopy]` – James P Jun 30 '16 at 14:10
3

This should do it:

// Access the dictionary you want to edit as a mutable copy
NSMutableDictionary *dict = [[[NSUserDefaults standardUserDefaults] objectForKey:@"dictKey"] mutableCopy];

// Remove the object for the key
[dict removeObjectForKey:@"keyToRemove"];

// Set the dictionary back in user defaults
[[NSUserDefaults standardUserDefaults] setObject:dict forKey:@"dictKey"];

// Save your changes:
// If you need
// In applicationDidEnterBackground: in iOS >= 7.0
// If you are using iOS < 7.0
[[NSUserDefaults standardUserDefaults] synchronize];
Wyetro
  • 8,439
  • 9
  • 46
  • 64
  • you don't need to synchronize. As of iOS 7 you don't need to call it. http://stackoverflow.com/questions/9647931/nsuserdefaults-synchronize-method – brl214 Jun 30 '16 at 14:24
  • "As of iOS 7 that is no longer the case so you might want to call synchronize in your app delegate's applicationDidEnterBackground: or register to the UIApplicationDidEnterBackgroundNotification notification to do that." --- It doesn't always call it when you want, so there's really no harm in using it (as long as you don't call it every time you are setting NSUserDefaults). – Wyetro Jun 30 '16 at 14:27
  • You just quoted/stated exactly what I was saying...Thank you? Why wouldn't you just call it one time when the app enters the background to avoid any performance issues. "Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes." – brl214 Jun 30 '16 at 14:34
  • Oh I see what you are refusing to understand, let me update my answer – Wyetro Jun 30 '16 at 14:35