联系人功能的需求一般都会有按照首字母排序,并且会要求同一个姓的就要连续起来中间不能穿插别的姓,百度了一下看到UILocalizedIndexedCollation给我们提供了很方便的排序方法,它不需要将中文转为拼音,但是有一个缺点就是如果姓氏存在多音字就无法区分(例如:姓增,它会被分配到C (ceng)组)

下面贴代码:
1,建一个类进行管理LinkManSort
.m文件
NSString *const CYPinyinGroupResultArray = @”CYPinyinGroupResultArray”;
NSString *const CYPinyinGroupCharArray = @”CYPinyinGroupCharArray”;
@implementation LinkManSort
// 按首字母分组排序数组 +(NSDictionary )sortObjectsAccordingToInitialWith:(NSArray )willSortArr SortKey:(NSString *)sortkey {
// 初始化UILocalizedIndexedCollation
UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
//得出collation索引的数量,这里是27个(26个字母和1个#)
NSInteger sectionTitlesCount = [[collation sectionTitles] count];
//初始化一个数组newSectionsArray用来存放最终的数据,我们最终要得到的数据模型应该形如@[@[以A开头的数据数组], @[以B开头的数据数组], @[以C开头的数据数组], ... @[以#(其它)开头的数据数组]]
NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
//初始化27个空数组加入newSectionsArray
for (NSInteger index = 0; index < sectionTitlesCount; index++) {
NSMutableArray *array = [[NSMutableArray alloc] init];
[newSectionsArray addObject:array];
}
NSLog(@"newSectionsArray %@ %@",newSectionsArray,collation.sectionTitles);
NSMutableArray *firstChar = [NSMutableArray arrayWithCapacity:10];
//将每个名字分到某个section下
for (id Model in willSortArr) {
//获取name属性的值所在的位置,比如"林丹",首字母是L,在A~Z中排第11(第一位是0),sectionNumber就为11
NSInteger sectionNumber = [collation sectionForObject:Model collationStringSelector:NSSelectorFromString(sortkey)];
//把name为“林丹”的p加入newSectionsArray中的第11个数组中去
NSMutableArray *sectionNames = newSectionsArray[sectionNumber];
[sectionNames addObject:Model];
NSString * str= collation.sectionTitles[sectionNumber];
[firstChar addObject:str];
NSLog(@"sectionNumbersectionNumber %ld %@",sectionNumber,str);
}
NSArray *firstCharResult = [self SortFirstChar:firstChar];
NSLog(@"firstCharResult== %@",firstCharResult);
//对每个section中的数组按照name属性排序
for (NSInteger index = 0; index < sectionTitlesCount; index++) {
NSMutableArray *personArrayForSection = newSectionsArray[index];
NSArray *sortedPersonArrayForSection = [collation sortedArrayFromArray:personArrayForSection collationStringSelector:@selector(name)];
newSectionsArray[index] = sortedPersonArrayForSection;
}
//删除空的数组
NSMutableArray *finalArr = [NSMutableArray new];
for (NSInteger index = 0; index < sectionTitlesCount; index++) {
if (((NSMutableArray *)(newSectionsArray[index])).count != 0) {
[finalArr addObject:newSectionsArray[index]];
}
}
return @{CYPinyinGroupResultArray:finalArr,
CYPinyinGroupCharArray:firstCharResult};另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
新闻标题:iOS实现联系人按照首字母进行排序的实例-创新互联
新闻来源:http://www.scyingshan.cn/article/dpeeeo.html


咨询
建站咨询
