I wrote this function that shuffles the contents of an NSString , and it seems to work, but from time to time it crashes. This may be a workaround, but I put the characters in the array, randomly change the elements in the array and then return the array back to the string.
I'm not sure what I'm doing is that it is unsafe, which leads to its collapse. I thought that maybe I am setting finalLettersString = result , but I also tried finalLettersString = [NSString stringWithString:result] , and that also fails. The reason I am confused is that it does not crash every time. I just press the shuffle button and sometimes it crashes. Any places I should see?
-(IBAction)shuffleLetters:(id)sender{ int length = [finalLettersString length]; NSMutableArray * letters = [NSMutableArray arrayWithCapacity:length]; NSLog(@"final letters: %@", finalLettersString); for(int i = 0; i < 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 >= 0; i--){ int j = arc4random() % (i + 1);
objective-c nsstring shuffle
jkeesh
source share