title: Shuffling Letters in an NSString in Objective-C
body: <p>I have written this function which shuffles the contents of a <code>NSString</code>, and it seems to work, but every now and then it crashes. This may be a roundabout way, but I put the characters into an array, swap the elements in the array randomly, and then turn the array back into a string.</p>
  
  <p>I'm not sure what I am doing that is unsafe which makes it crash. I thought it was possibly that I am setting <code>finalLettersString = result</code>, but I also tried <code>finalLettersString = [NSString stringWithString:result]</code> and that also crashes. The reason I am confused is because it does not crash every time. I just keep pressing the shuffle button, and sometimes it crashes. Any places I should look?</p>
  
  <pre><code>/* This function shuffles the letters in the string finalLettersString */
  
  -(IBAction)shuffleLetters:(id)sender{
      int length = [finalLettersString length];
      NSMutableArray * letters = [NSMutableArray arrayWithCapacity:length]; 
      NSLog(@"final letters: %@", finalLettersString);
      for(int i = 0; i &lt; length; i++){
          char ch = [finalLettersString characterAtIndex:i];
          NSLog(@"%c", ch);
          NSString * cur = [NSString stringWithFormat:@"%c", ch];
          [letters insertObject:cur atIndex:i];
      }
  
      NSLog(@"LETTERS:: %@", letters);
  
      for(int i = length - 1; i &gt;= 0; i--){
          int j = arc4random() % (i + 1);
          //NSLog(@"%d %d", i, j);
          //swap at positions i and j
          NSString * str_i = [letters objectAtIndex:i];
          [letters replaceObjectAtIndex:i withObject:[letters objectAtIndex:j]];
          [letters replaceObjectAtIndex:j withObject:str_i];      
      }
      NSLog(@"NEW SHUFFLED LETTERS %@", letters);
  
      NSString * result = @"";
      for(int i = 0; i &lt; length; i++){
          result = [result stringByAppendingString:[letters objectAtIndex:i]];
      }
  
      NSLog(@"Final string: %@", result);
      finalLettersString = result;
      finalLetters.text = finalLettersString;
  }
  </code></pre>