これは奇妙なものです...
定期的に、ユーザーが私のアプリで新しいトップスコアを達成したかどうかを確認しています。これが私のコードです:
- (void) newTopScore
{
// pull old top score from the database
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *getBoardsAndScores = [defaults dictionaryRepresentation];
NSMutableArray *boardsAndScores = [[getBoardsAndScores objectForKey:@"boardsAndScores"] mutableCopy];
NSMutableDictionary *boardAndScoreObject = [[boardsAndScores objectAtIndex:gameBoardIndex] mutableCopy];
NSString *topscore = [boardAndScoreObject objectForKey:@"topscore"];
NSLog(@"topscore in value: %i", [topscore intValue]);
if ([topscore intValue] == 0)
{
NSString *topscoreString = [[NSString alloc] initWithFormat:@"%i", [self countCurrentPegs]];
NSMutableArray *mutableBoardsAndScores = [boardsAndScores mutableCopy];
[[mutableBoardsAndScores objectAtIndex:gameBoardIndex] setObject:topscoreString forKey:@"topscore"];
[defaults setObject:mutableBoardsAndScores forKey:@"boardsAndScores"];
[defaults synchronize];
}
else if ([self countCurrentPegs] < [topscore intValue])
{
NSString *topscoreString = [[NSString alloc] initWithFormat:@"%i", [self countCurrentPegs]];
NSMutableArray *mutableBoardsAndScores = [boardsAndScores mutableCopy];
[[mutableBoardsAndScores objectAtIndex:gameBoardIndex] setObject:topscoreString forKey:@"topscore"];
[defaults setObject:mutableBoardsAndScores forKey:@"boardsAndScores"];
[defaults synchronize];
}
}
ifとelseの両方で、コードが正常に機能する場合があります。次のエラーが発生することがあります。
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]:
mutating method sent to immutable object'
ブレークポイントを設定し、プログラムを1行ずつステップ実行してみました。クラッシュはややランダムに見え、パターンを理解できません。通常、2番目にクラッシュします...
[[mutableBoardsAndScores objectAtIndex:gameBoardIndex] setObject:topscoreString forKey:@"topscore"];
...ライン。
オブジェクトは変更可能です。または少なくともそうでした。なぜ変わるのですか?
アドバイスをいただければ幸いです。
ありがとう。