我已经编写了这个函数,它对 a 的内容进行了洗牌NSString
,它似乎可以工作,但它时不时地崩溃。这可能是一种迂回的方式,但我将字符放入数组中,随机交换数组中的元素,然后将数组转回字符串。
我不确定我在做什么是不安全的,这会导致它崩溃。我认为这可能是我正在设置finalLettersString = result
,但我也尝试过,但finalLettersString = [NSString stringWithString:result]
它也崩溃了。我感到困惑的原因是因为它不会每次都崩溃。我只是一直按随机播放按钮,有时它会崩溃。有什么地方值得看吗?
/* 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 < 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);
//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 < length; i++){
result = [result stringByAppendingString:[letters objectAtIndex:i]];
}
NSLog(@"Final string: %@", result);
finalLettersString = result;
finalLetters.text = finalLettersString;
}