我已经编写了这个函数来调整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; }
解决方法
最好将字符串的内容复制到unichar类型的临时缓冲区中并对缓冲区的内容进行随机播放,而不是创建大量的小字符串.
NSUInteger length = [finalLetteRSString length]; if (!length) return; // nothing to shuffle unichar *buffer = calloc(length,sizeof (unichar)); [finalLetteRSString getCharacters:buffer range:NSMakeRange(0,length)]; for(int i = length - 1; i >= 0; i--){ int j = arc4random() % (i + 1); //NSLog(@"%d %d",j); //swap at positions i and j unichar c = buffer[i]; buffer[i] = buffer[j]; buffer[j] = c; } NSString *result = [NSString stringWithCharacters:buffer length:length]; free(buffer); // caution,autoreleased. Allocate explicitly above or retain below to // keep the string. finalLetteRSString = result;
您需要注意的几件事情:
> Unicode字符串可以包含复合字符和代理项对.将这些转移到最有可能导致无效的字符串.虽然代理对很少见,但是发现字符é由两个字符组成(基本小写字母e和组合的尖锐重音)并不罕见.>对于大字符串,它可能会导致内存问题,因为最终使用的空间是原始字符串的3倍(原始字符串为1倍,我们使用的缓冲区为2倍,新字符串为3倍,然后返回一旦我们释放缓冲区,就降低到2倍.