这里用到了一个三方库:PinYin4Objc github地址:https://github.com/kimziv/PinYin4Objc
//处理联系人列表,包括按ABC...XYZ#顺序排序并分组//参数followList是联系人模型数组//block中返回的参数list表示的是ABC...XYZ#数组,dict表示的是@{@"A":对应的联系人数组,@"B":...}- (void)handlesectionTitleList:(NSArray *)followList resultBlock:(void(^)(NSDictionary *dict,NSArray *list)) resultBlock{ NSMutableDictionary *tempDic = [[NSMutableDictionary alloc]init]; for(ContactsModel *contact in followList)//ContactsModel:联系人模型 { HanyuPinyinOutputFormat *formatter = [[HanyuPinyinOutputFormat alloc] init]; formatter.caseType = CaseTypeLowercase; formatter.vCharType = VCharTypeWithV; formatter.toneType = ToneTypeWithoutTone; if (contact.showName.length>0) { NSString *tempStr =[contact.showName substringToIndex:1];//列表中显示的名字 if ([tempStr isJudgeTheillegalCharacter]) {//判断首字符是否是数字或是非法字符 [tempDic setObject:contact forKey:@"#"]; }else { NSString *outputPinyin=[PinyinHelper toHanyuPinyinStringWithNSString:contact.showName withHanyuPinyinOutputFormat:formatter withNSString:@""]; [tempDic setObject:contact forKey:[[outputPinyin substringToIndex:1] uppercaseString]]; } } } NSMutableArray *sectionTitleList = [[NSMutableArray alloc]initWithArray:tempDic.allKeys]; NSMutableDictionary *nameDic = [NSMutableDictionary new]; for (NSString *letter in sectionTitleList) { NSMutableArray *tempArry = [[NSMutableArray alloc] init]; for (NSInteger i = 0; i<followList.count; i++) { ContactsModel *contact = followList[i]; HanyuPinyinOutputFormat *formatter = [[HanyuPinyinOutputFormat alloc] init]; formatter.caseType = CaseTypeUppercase; formatter.vCharType = VCharTypeWithV; formatter.toneType = ToneTypeWithoutTone; if (contact.showName.length >0) { NSString *tempStr =[contact.showName substringToIndex:1]; if ([letter isEqualToString:@"#"]) { if ([tempStr isJudgeTheillegalCharacter]) {//判断首字符是否是数字或是非法字符 [tempArry addObject:contact]; } }else { //把friend的userName汉子转为汉语拼音,比如:张磊---->zhanglei NSString *outputPinyin=[PinyinHelper toHanyuPinyinStringWithNSString:contact.showName withHanyuPinyinOutputFormat:formatter withNSString:@""]; if ([letter isEqualToString:[[outputPinyin substringToIndex:1] uppercaseString]]) { [tempArry addObject:contact]; } } } } [nameDic setObject:tempArry forKey:letter]; } sectionTitleList = [[NSMutableArray alloc]initWithArray:tempDic.allKeys]; [sectionTitleList removeObject:@"#"]; //排序,排序的根据是字母 NSComparator cmptr = ^(id obj1, id obj2){ if ([obj1 characterAtIndex:0] > [obj2 characterAtIndex:0]) { return (NSComparisonResult)NSOrderedDescending; } if ([obj1 characterAtIndex:0] < [obj2 characterAtIndex:0]) { return (NSComparisonResult)NSOrderedAscending; } return (NSComparisonResult)NSOrderedSame; }; sectionTitleList = [[NSMutableArray alloc]initWithArray:[sectionTitleList sortedArrayUsingComparator:cmptr]]; if ([[nameDic objectForKey:@"#"] count] >0) { [sectionTitleList addObject:@"#"]; } if (resultBlock) { resultBlock(nameDic,sectionTitleList); }}若有侵权,请联系我
新闻热点
疑难解答