【问题标题】:NSUserDefaults objectForKey keeps returning nil, even when key existsNSUserDefaults objectForKey 一直返回 nil,即使 key 存在
【发布时间】:2014-08-14 06:13:58
【问题描述】:

我正在尝试将数据保存在 NSUserDefaults 中。此代码(和应用程序)第一次循环时,它应该通过 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

【问题讨论】:

  • 尝试使用setObject:forKey。如果这不起作用,请在设置所有值后致电synchronize

标签: ios nsuserdefaults


【解决方案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 中,因此您正在检查键“BoughtItem%d”是否存在,但您正在设置“BoughtItem0”...

【讨论】:

  • 谢谢!这就是我的问题的答案。不敢相信我没有看到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多