這是一個奇怪的一個錯誤時,「變異發送到不可變對象方法」 ......奇怪的添加對象的可變數組
週期性我檢查,如果用戶已經在我的應用程序實現了新的最高分。這裏是我的代碼:
- (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'
我試過設置斷點並逐行通過程序。崩潰似乎有些隨意,我無法制定一個模式。它通常在第二個崩潰...
[[mutableBoardsAndScores objectAtIndex:gameBoardIndex] setObject:topscoreString forKey:@"topscore"];
...線。
對象IS可變。或者至少是這樣。它爲什麼會改變?
任何建議的幫助將不勝感激。
謝謝。
它不再有錯誤,但它也停止更新NSUserDefaults。 – Jon 2012-04-18 08:14:49
我把完整的代碼推到github上:https://github.com/jonwheatley/peg – Jon 2012-04-18 08:15:27
我編輯了我的答案,你能試試嗎? – Manuel 2012-04-18 09:01:11