将对象设置为NSMutableDictionary且没有崩溃日志时,应用程序崩溃

时间:2012-12-30 03:44:02

标签: objective-c xcode cocos2d-iphone nsdictionary nsmutabledictionary

我尝试为我的游戏制作一个简单的分数系统,我正在使用字典并使用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行时,一切正常。任何人都可以,如果有什么事情导致崩溃?提前谢谢。

1 个答案:

答案 0 :(得分:7)

你的问题就在这一行:

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

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

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

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

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

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

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

相关问题