如何优化此循环?

时间:2010-12-25 23:42:55

标签: iphone objective-c c optimization loops

我有一段代码返回一个代表“搜索结果”的超长字符串。每个结果都由双HTML断点符号表示。例如:

  

Result1< br>< br>结果2< br>< br> Result3

我有以下循环,它接受每个结果并将其放入一个数组中,去掉中断指示符“kBreakIndicator”(< br>< br>)。问题是这个lopp的执行时间太长了。有一些结果很好,但一旦你达到一百个结果,它会慢大约20-30秒。这是不可接受的表现。我该怎么做才能提高绩效?

这是我的代码:

content是原始的NSString。

  NSMutableArray *results = [[NSMutableArray alloc] init];

  //Loop through the string of results and take each result and put it into an array
   while(![content isEqualToString:@""]){
   NSRange rangeOfResult = [content rangeOfString:kBreakIndicator];
   NSString *temp = (rangeOfResult.location != NSNotFound) ? [content substringToIndex:rangeOfResult.location] : nil; 
   if (temp) {
    [results addObject:temp];
    content = [[[content stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@%@", temp, kBreakIndicator] withString:@""] mutableCopy] autorelease];
   }else{
    [results addObject:[content description]];
    content = [[@"" mutableCopy] autorelease];
   }
  }
//Do something with the results array.
[results release];

2 个答案:

答案 0 :(得分:3)

您可以做的是首先使用NSString的{​​{1}}方法为您提供componentsSeparatedByString:,如下所示:

编辑:假设您的NSArray常量为kBreakIndicator

<br>

@ invariant回答的结果http://cl.ly/3Z112M3z3K1V2t0A3N2L

我的回答结果http://cl.ly/371b2j2H0Y1E110D2w0I

如果NSArray *temp_results = [content componentsSeparatedByString:kBreakIndicator]; NSMutableArray *results = [[NSMutableArray alloc] init]; for(NSString *result in temp_results) { if(result.length == 0) continue; [results addObject:result]; } //do something with results... [results release]; 常量为kBreakIndicator

<br><br>

答案 1 :(得分:2)

这应该这样做:

NSArray *results = [content componentsSeparatedByString:@"<br><br>"];