ios搜尋(可實現模糊搜尋 支援拼音檢索 首字母等)
阿新 • • 發佈:2019-01-08
一、搜框中輸入關鍵字的事件響應
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
NSLog(@"輸入的關鍵字是---%@---%lu",searchText,(unsigned long)searchText.length);
//需要事先清空存放搜尋結果的陣列
[self.resultArray removeAllObjects];
//加個多執行緒,否則數量量大的時候,有明顯的卡頓現象
//這裡最好放在資料庫裡面再進行搜尋,效率會更快一些
dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
dispatch_async(globalQueue, ^{
if (searchText!=nil && searchText.length>0) {
//遍歷需要搜尋的所有內容,其中self.dataArray為存放總資料的陣列
for (DataModel *model in self.dataArray) {
NSString *tempStr = model.content;
//----------->把所有的搜尋結果轉成成拼音
NSString *pinyin = [self transformToPinyin:tempStr];
NSLog(@"pinyin--%@",pinyin);
if ([pinyin rangeOfString:searchText options:NSCaseInsensitiveSearch].length >0 ) {
//把搜尋結果存放self.resultArray陣列
[self.resultArray addObject:model];
}
}
}else{
self.resultArray = [NSMutableArray arrayWithArray:self.dataArray];
}
//回到主執行緒
dispatch_async(dispatch_get_main_queue(), ^{
[_tableView reloadData];
});
});
}
二、獲取漢字轉成拼音字串 通訊錄模糊搜尋 支援拼音檢索 首字母 全拼 漢字 搜尋
- (NSString *)transformToPinyin:(NSString *)aString
{
//轉成了可變字串
NSMutableString *str = [NSMutableString stringWithString:aString];
CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
//再轉換為不帶聲調的拼音
CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
NSArray *pinyinArray = [str componentsSeparatedByString:@" "];
NSMutableString *allString = [NSMutableString new];
int count = 0;
for (int i = 0; i < pinyinArray.count; i++)
{
for(int i = 0; i < pinyinArray.count;i++)
{
if (i == count) {
[allString appendString:@"#"];
//區分第幾個字母
}
[allString appendFormat:@"%@",pinyinArray[i]];
}
[allString appendString:@","];
count ++;
}
NSMutableString *initialStr = [NSMutableString new];
//拼音首字母
for (NSString *s in pinyinArray)
{
if (s.length > 0)
{
[initialStr appendString: [s substringToIndex:1]];
}
}
[allString appendFormat:@"#%@",initialStr];
[allString appendFormat:@",#%@",aString];
return allString;
}