1

I'm trying to save data in NSUserDefaults. The very first time this code (and app) loops, it should go through the if-statement. Because no data was saved in NSUserdefaults was saved yet with the names: BoughtItem0, BoughtItem1, BoughtItem2, BoughtItem3.

But somehow after looping the code for the first time, and so starting my app for the second time it keeps going through the if-statement. What's wrong in my code?

for (int i = 0; i < [shopPrices count]; i++)
{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"BoughtItem%d"] == nil)
    {
        [[NSUserDefaults standardUserDefaults] setValue:@"NONO" forKey:[NSString stringWithFormat:@"BoughtItem%d", i]];
        NSLog(@"BoughtItem%d", i);
    }
    else
    {
        NSLog(@"No new bought item keys made");
    }
}

the output is:

BoughtItem0
BoughtItem1
BoughtItem2
BoughtItem3
modusCell
  • 13,151
  • 9
  • 53
  • 80
Viktor De Bock
  • 139
  • 1
  • 2
  • 17

1 Answers1

1

Your problem is that you have used a format string in your call to objectForKey but you have omitted the call to stringWithFormat. I think what you meant was -

for (int i = 0; i < [shopPrices count]; i++)
{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"BoughtItem%d",i]] == nil)
    {
        [[NSUserDefaults standardUserDefaults] setValue:@"NONO" forKey:[NSString stringWithFormat:@"BoughtItem%d", i]];
        NSLog(@"BoughtItem%d", i);
    }
    else
    {
        NSLog(@"No new bought item keys made");
    }
}

You had it in the setValue, just not in your if, so you were checking for the existence of the key "BoughtItem%d", but you were setting "BoughtItem0"...

Paulw11
  • 108,386
  • 14
  • 159
  • 186