App crashing during NSUserDefault data removal

490 views Asked by At

When I call this function my app gets crash.
I got this error : [__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[1].
How i can resolve it please help if you know.

NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
      NSDictionary *dict = [defs dictionaryRepresentation];
      for (id key in dict)
      {
          NSObject * object = [dict objectForKey:key];
          if(object != nil)
          {
              [defs removeObjectForKey:key];
              [defs synchronize];
          }
      }  
3

There are 3 answers

8
Chatar Veer Suthar On BEST ANSWER

Kindly use following code. It should help you

NSString *applicationDomain = [[NSBundle mainBundle] bundleIdentifier];

[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:applicationDomain];

You can also use

    NSDictionary *defaultsDictionary = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
    for (NSString *key in [defaultsDictionary allKeys]) {
                        [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
    }

[[NSUserDefaults standardUserDefaults] synchronize]; //outside loop.

NOTE: The crash which you are mentioning is regarding setValue ForKey in a Dictionary. Kindly user breakpoint and see where you are inserting nil value in Dictionary.

0
zizoodiesel On

try adding the keys of the desired entries into NSArray inside the loop then do removeObjectsForKeys:array outside the loop

It's preferable to not remove entries while enumerating inside a for loop

1
user3182143 On

My solution for your question is

NSUserDefaults *defs  = [NSUserDefaults standardUserDefaults];
NSDictionary *dict = [userDefaults dictionaryRepresentation];
for (id key in dict) {
    [dict removeObjectForKey:key];
}
[defs synchronize];