我不确定我在做什么不安全会导致它崩溃.我以为我可能正在设置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倍.
总结以上是内存溢出为你收集整理的Objective-C中的NSString中的Shuffling Letters全部内容,希望文章能够帮你解决Objective-C中的NSString中的Shuffling Letters所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)