Search code examples
iphoneobjective-ccocoa-touchnsuserdefaultssynchronize

NSUserDefaults standardUserDefaults returns nil


I've seen a couple of questions about this, but I don't think these answer my problem.

In my method I have... within an if statement, which I use to set a default value upon first launch of my app.

NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];
[myDefaults setObject:@"1" forKey:kNSUAccountSelection];
[myDefaults synchronize];

Further down I do the same thing with another key.

Then I run this...

NSString *account_name = [[accountArray objectAtIndex:[accountArray 
   indexOfObject:[[NSUserDefaults standardUserDefaults] 
   objectForKey:kNSUAccountSelection]]] objectForKey:@"Account_Name"];

Which results in an error.

Terminating app due to uncaught exception 'NSRangeException', reason: ' -[NSMutableArray objectAtIndex:]: index 2147483647 beyond bounds [0 .. 0]'

So I tried... directly before that line...

NSUserDefaults *myDefaults2 = [NSUserDefaults standardUserDefaults];
NSString *str = [myDefaults2 stringForKey:kNSUAccountSelection];

And str returns nil.

In my constants.h file I have...

#define kNSUAccountSelection @"accountselection"

Yes, accountArray is populated from my database and has values.

I don't understand why I'm getting nil and what I have to do fix this ? From what I've read this should work.


Solution

  • I suggest breaking your 1-liner down a bit.

    NSString *account_name = [[accountArray objectAtIndex:[accountArray 
       indexOfObject:[[NSUserDefaults standardUserDefaults] 
       objectForKey:kNSUAccountSelection]]] objectForKey:@"Account_Name"];
    

    Specifically

    [accountArray 
           indexOfObject:[[NSUserDefaults standardUserDefaults] 
           objectForKey:kNSUAccountSelection]]
    

    is causing your error.

    the indexOfObject is returning NSNotFound

    NSNotFound 2147483647
    

    EDIT

    Your comment confuses me. Let's call

    int index = [accountArray 
               indexOfObject:[[NSUserDefaults standardUserDefaults] 
               objectForKey:kNSUAccountSelection]];
    

    The 1-liner I referenced is now

    NSString *account_name = [[accountArray objectAtIndex:index] objectForKey:@"Account_Name"];
    

    Your comment references

    int num = [[accountArray objectAtIndex:[accountArray indexOfObject:[[NSUserDefaults standardUserDefaults] objectForKey:kNSUAccountSelection]]] intValue];
    

    becomes

    int num = [[accountArray objectAtIndex:index] intValue];
    

    What is supposed to be inside of accountArray? dictionaries, strings or numbers? I know you can mix and match whatever objects you want inside the array, but what are you expecting

    [accountArray objectAtIndex:index]
    

    to be?