NSDictionary不存储信息

时间:2012-06-01 18:25:43

标签: iphone objective-c cocoa-touch

由于一些奇怪的原因,golferStats没有正确存储信息......

我在这段代码中删除了一堆内容,以便为什么它仍然不起作用?

问题:最后一个NSLOG在返回一个巨大的数组时返回nil ...

NSMutableDictionary *golferStats = [[NSMutableDictionary alloc] init];
golferStats = [userDefaults objectForKey:@"golferStats"];

[golferStats setObject:golferTwoIconCounter forKey:golferName]; //golferName is k

[userDefaults setObject:golferStats forKey:@"golferStats"];
[userDefaults synchronize];
NSLog(@"SAVED SCORE CARD");
NSLog(@"%@",[golferStats objectForKey:@"k"]);

2 个答案:

答案 0 :(得分:2)

NSMutableDictionary *golferStats = [[NSMutableDictionary alloc] init];

<击> golferStats = [userDefaults objectForKey:@"golferStats"];

...

[golferStats release];

首先创建一个NSDictionary,然后分配它,从而泄漏内存,并可能从用户默认值中恢复nilsetObject:forKey:字典中的nil是无操作,然后您将其重新设置为用户默认值。

修改

首先检查是否有字典:

NSDictionary *golferStats = [userDefaults objectForKey:@"golferStats"];
if (golferStats == nil) {
    golferStates = [NSDictionary dictionary]; // this will not leak
}
...

答案 1 :(得分:1)

如果要在已经存在 的情况下保留字典的现有内容,请执行以下操作:

NSMutableDictionary *golferStats = [userDefaults objectForKey:@"golferStats"];
if (!golferStats) golferStats = [[[NSMutableDictionary alloc] init] autorelease];

[golferStats setObject:golferTwoIconCounter forKey:golferName];
[userDefaults setObject:golferStats forKey:@"golferStats"];
[userDefaults synchronize];

// no [golferStats release] because of autorelease above