我有一段代码,它返回一个表示“搜索结果”的超长字符串。每个结果都由一个双HTML中断符号表示。例如:
结果1
结果2
结果3
我得到了下面的循环,将每个结果放入一个数组中,去掉break指示符,“kBreakIndicator
”(
)。问题是这个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];
最佳答案
您可以首先使用NSString
的componentsSeparatedByString:
方法,该方法将为您提供一个NSArray
,如下所示:
编辑:假设您的kBreakIndicator
常量为<br>
:
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];
@invariant的答案的结果:http://cl.ly/3Z112M3z3K1V2t0A3N2L
我的回答结果:http://cl.ly/371b2j2H0Y1E110D2w0I
如果您的
kBreakIndicator
常数是<br><br>
:NSArray *result = [content componentsSeparatedByString:kBreakIndicator];
关于iphone - 如何优化此循环?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4532170/