0

我尝试为我的游戏制作一个简单的分数系统,我正在使用字典并使用 NSUserDefaults 保存它来存储玩家的分数。但是,当我尝试为现有键/值设置新分数时,应用程序崩溃,没有任何控制台日志消息,并且 xcode 切换到我无法读取的汇编代码。我知道它在哪里崩溃,因为我设置了异常并且它显示了它在哪一行被调用。如果有任何改变,我也会使用 cocos2d。

这是代码:

//creates key for the right level     
NSString *currentLevelString = [NSString stringWithFormat:@"Level%i",numberOfCurentLevel];


 //checking if dictionary is empty, if empty then it means the game is played for the first time
 NSMutableDictionary *dictionary = [[[NSMutableDictionary alloc]init]autorelease];
//ud is the UserDefaults

 dictionary = [ud objectForKey:@"dictionaryWithScores"];

 if ([dictionary objectForKey:@"Level5"] == nil) {
     //assigning first values for empty dictionary
     dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"ScoreList" ofType:@"plist"]];
     NSLog(@"dictionary was empty");
 }
 //NSLog(@"now dictionary shoud not be empty %@",dictionary);
 //calculating current score for this level
 double currentScore = (numberOfCurentLevel * elementsFound)/9.0;///timeInSeconds;
 double previousScore = [[dictionary objectForKey:currentLevelString]doubleValue];//taking previous score for thi level
 NSLog(@"currentScore: %f \n previousScore: %f",currentScore,previousScore);
 //checking whether current score is greater than the previous one
 if (currentScore > previousScore)
 {
     NSLog(@"dictionary just before the crash: %@",dictionary);
     //if new score is greater then update the dictionary
     NSString *currentScoreString = [NSString stringWithFormat:@"%f",currentScore];

//it crashes on this line seObject

     [dictionary setObject:currentScoreString forKey:currentLevelString];
     [ud setObject:dictionary forKey:@"dictionaryWithScores"];
     [ud synchronize];

//calculating total score (score for each level + next one)
 double overallScore = 0;
 for (int i=1; i <= 101; i++) {
     //adding scores for each level to each other
     overallScore = overallScore + [[dictionary objectForKey:[NSString stringWithFormat:@"Level%i",i]]doubleValue];
    // NSLog(@"overal score: %f",overallScore);
 }

当我评论 setObject 行时,一切正常。任何人都可以,如果有什么导致崩溃?先感谢您。

4

1 回答 1

7

你的问题是这一行:

dictionary = [ud objectForKey:@"dictionaryWithScores"];

那是返回一个不可变的字典,所以没有setObject:方法。您将 plist 文件加载到可变字典中,但该字典中的所有字典仍然是不可变的。

要将不可变字典转换为可变字典,请执行以下操作:

dictionary = [[ud objectForKey:@"dictionaryWithScores"] mutableCopy];

您可能还想将刚刚制作的可变副本保存回ud字典中:

[ud setObject:dictionary forKey:@"dictionaryWithScores"];

PS:我不确定您为什么看不到日志消息;你应该看到一个。

于 2012-12-30T03:56:14.223 回答