【发布时间】:2018-11-22 08:20:05
【问题描述】:
我正在一个函数中搜索大约 100k 个字符串:
results = [NSMutableArray new];
for (int n = 0; n < (int)_donkey.searchStrings.count; n++){
if ([[_donkey.searchStrings[n] lowercaseString] rangeOfString:tf.text.lowercaseString].location != NSNotFound){
[results addObject:_donkey.formattedStrings[n]];
}
}
其中tf.text 是用户在UITextField 中输入的文本。性能很慢,我觉得有一种更好的搜索方式,而不是直接的字符串比较。
被搜索的字符串格式如下:“attributeA attributeB attributeC”,所以如果在attributeA之前输入attributeB,它不会作为结果出现,这是应该的。
【问题讨论】:
-
也许你可以用
NSPredicate和/或NSRegularExpression来做到这一点。 -
@Koen 这两者都会比有目的地编写的代码慢得多。
-
与您的性能问题无关,但不要在循环中使用
int。count返回NSUInteger。数组访问使用NSUInteger。所以使用NSUInteger作为循环变量(并去掉演员表)。 -
@rmaddy 谢谢,出于某些(非逻辑)原因,我更喜欢整数,但应该学会放弃不良的编码习惯 :)
标签: ios objective-c search nsstring