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