iosobjective-ciphonensuserdefaultsiphone-sdk-4.1

App crashing during NSUserDefault data removal


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];
          }
      }  

Solution

  • 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.