title: Strange "mutating method sent to immutable object" error when adding an object to a mutable array
body: <p>This is a strange one...</p>
  
  <p>Periodically I am checking if the user has achieved a new top score in my app.  Here is my code:</p>
  
  <pre><code>- (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] &lt; [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];
      }
  
  }
  </code></pre>
  
  <p>Sometimes the code works just fine, both for the if and the else. Sometimes though I get the following error:</p>
  
  <pre><code>*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: 
  mutating method sent to immutable object'
  </code></pre>
  
  <p>I've tried setting break points and stepping through the program line by line. The crash seems somewhat random and I can't work out a pattern. It usually crashes on the second...</p>
  
  <pre><code>[[mutableBoardsAndScores objectAtIndex:gameBoardIndex] setObject:topscoreString forKey:@"topscore"];
  </code></pre>
  
  <p>...line. </p>
  
  <p>The object IS mutable. Or at least it was. Why is it changing? </p>
  
  <p>Any help of advice would be very appreciated. </p>
  
  <p>Thanks.</p>