即使密钥存在,NSUserDefaults objectForKey也会保持返回nil

时间:2014-08-13 21:54:07

标签: ios nsuserdefaults

我试图在NSUserDefaults中保存数据。这个代码(和app)第一次循环,它应该通过if语句。因为没有数据保存在NSUserdefaults中,但保存了名称:BoughtItem0,BoughtItem1,BoughtItem2,BoughtItem3。

但是在第一次循环代码之后不知怎的,所以第二次启动我的应用程序它继续通过if语句。我的代码有什么问题?

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");
    }
}

输出是:

BoughtItem0
BoughtItem1
BoughtItem2
BoughtItem3

1 个答案:

答案 0 :(得分:1)

您的问题是您在objectForKey的通话中使用了格式字符串,但您忽略了对stringWithFormat的调用。我想你的意思是 -

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");
    }
}

你在setValue中有它,而不是在你的if中,所以你正在检查是否存在键&#34; BoughtItem%d&#34;,但是你设置了&#34; BoughtItem0& #34; ...