我知道已经有很多问题被问到了,但是我要再提出一个问题。我有一个数组包含大量(数千条记录)NSDictionary
格式的数据,我正在尝试在字典中的键中执行搜索到数组中。
我正在UITextField
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
数据源方法中执行搜索,
我的搜索要求在整个字符串中,
示例字符串,
aaa, abeb, abcd, abbec 类似字符串
搜索流程,
如果a
返回我所有的字符串,
如果aa
只返回 aaa,
如果ab
返回abeb, abcd, abbec
喜欢,
重要的是,如果cd
它只返回 abcd
我用这些方法试过了,
使用NSPredicates
NSLog(@"start search at : %@",[NSDate date]);
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Name contains[cd] %@", matchString];
searchArray = [[meadArray filteredArrayUsingPredicate:predicate] mutableCopy];
NSLog(@"Search found count = %d",searchArray.count);
[tableCheck reloadData];
NSLog(@"End search at : %@",[NSDate date]);
另一种方式 - 通过迭代,
NSLog(@"start search at : %@",[NSDate date]);
for (NSDictionary *word in arrayNames)
{
if ([matchString length] == 0)
{
[searchArray addObject:word];
continue;
}
NSRange lastRange = [[[word valueForKey:@"Name"] uppercaseString] rangeOfString:upString];
if ( lastRange.location != NSNotFound)
{
if(range.location == 0 || lastRange.location == 0)
{
[searchArray addObject:word];
}
}
}
NSLog(@"End search at : %@",[NSDate date]);
这两种方法都运行良好,结果如我所料,但仅在模拟器中!当我在设备中测试相同的内容时,根据搜索的扩展,它大约需要 1 / 2 / 3 秒,首先说如果我输入,a
它需要 3 秒,因为aa
它需要大约 2 秒,依此类推。IT LOOKS CLUMSY ON DEVICE, ANY PRESSED KEY WILL BE REMAIN HIGHLIGHTED UNTIL SEARCH NOT DONE
.
有什么方法可以让我使用我正在使用的相同方法或任何其他替代方法执行更快的搜索!
更新 1
还尝试使用CFArrayBSearchValues它只返回搜索字符串的索引,但我想要返回所有匹配的字符串的东西。
unsigned index = (unsigned)CFArrayBSearchValues((CFArrayRef)meadArray, CFRangeMake(0, CFArrayGetCount((CFArrayRef)meadArray)), (CFStringRef)matchString,(CFComparatorFunction)CFStringCompare, NULL);
更新 2
As per the Alladinian
comment, I performed search operation in background thread, yes now its not lock UI, but still searching is too slow, What I'm doing is, performing a selector for some delay say 0.25 seconds, also cancelling any previous selector calls, and then performing searching in background, also reloading table in main thread. Its working like, If I type character with some delay, its works good, but if I type whole word at once, it will loading / updating table as per the characters pressed, at last it will show me the actual output, takes 3-4 seconds for showing the actual content.
Any suggestion or help highly appreciated!