`[NSUserDefaults standardUserDefaults]` returns nil

3.5k Views Asked by At

I want to save some user preferences, but

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

just returns nil.

iOS-Developper Library says, that this should return the existing shared defaults object or create one if none exists... What am I missing?

I also use Appirater and there all this stuff seems also not to work...

This code gets called when the user pushes a button...

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int index = ([defaults integerForKey:@"BackgroundColorSpecifier"]+ 1)%self.backgroundColors.count;
[defaults setInteger:index forKey:@"BackgroundColorSpecifier"];
[defaults synchronize];

This gets called in application: didFinishLaunchingWithOptions:

NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
[standardDefaults registerDefaults:@{@"BackgroundColorSpecifier": @0}];
[standardDefaults synchronize];

When I debug this code snippets the green "position-indicator" jumps around in a very strange manner...

I don't have any clue, whats going on... Please help!

2

There are 2 best solutions below

0
On BEST ANSWER

This is far more likely to be a problem with the debugger than anything else, particularly with your other issues. I've seen similar things in my own projects but don't have a reliable way of clearing it out other than the usual restart / clean options.

NSLogs will usually give more consistent results than the debugger if the debugger is having an off day.

NSUserDefaults isn't broken. We'd have heard about it by now.

0
On

you can use this function to log you userDefaults dic

 - (void)logCache
    {
        NSDictionary * dic = [[NSBundle mainBundle] infoDictionary];
        NSString *bundleId = [dic  objectForKey: @"CFBundleIdentifier"];
        NSUserDefaults *appUserDefaults = [[NSUserDefaults alloc] init];
        NSDictionary *cacheDic = [appUserDefaults persistentDomainForName: bundleId];
        NsLog(@"cacheDic::%@",cacheDic);
    }