一、搜框中输入关键字的事件响应
-(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;
}