美文网首页
根据名字首字母对数组排序并分组

根据名字首字母对数组排序并分组

作者: 谢涙 | 来源:发表于2016-05-23 22:35 被阅读728次

在oc开发中,请求下来的数据大多数是无规则的,但是boss要求要排序并且加上索引,这样用户就可以在大量的数组中准确的定位到自己所要找的内容,然而很多初学者对oc中封装的类不是很了解,所以用大篇幅的代码来做判断,整理数组。

在这,给大家发一个小Demo,希望对大家有所帮助,同时,有错误的地方希望大大们批评指教。

#pragma mark-通过名称首字母给对象排序并分组。(这段代码可以直接复制粘贴进自己的工程)

-(NSMutableArray *)sortObjectsAccordingToInitialWith:(NSArray *)arr {

//初始化UILocalizedIndexedCollation

UILocalizedIndexedCollation *xlCollation = [UILocalizedIndexedCollation currentCollation];

//得出collation索引的数量

NSInteger xlTitlesCount = [[xlCollation sectionTitles]count];

//数组xlNewArray用来存放最终的数据

NSMutableArray *xlNewArray = [[NSMutableArray alloc]initWithCapacity:xlTitlesCount];

//初始化27个空数组加入newSectionsArray( 26个英文字母加一个#号)

for(NSInteger i = 0; i < xlTitlesCount; i++) {

NSMutableArray *array = [[NSMutableArray alloc]init];

[xlNewArray addObject:array];

}

//将每个名字分到某个section下(CarTypeModel是你创建的model)

for(CarTypeModel *Model in _carProductArray) {

//获取name属性的值所在的位置

NSInteger section = [xlCollation sectionForObject:Model collationStringSelector:@selector(name)];

//通过name把对应的Model放到对应的section中。

NSMutableArray *sectionNames = xlNewArray[section];

[sectionNames addObject:Model];

}

//对每个section中的数组按照name属性排序

for(NSInteger i =0; i < xlTitlesCount; i++) {

NSMutableArray *modelSection = xlNewArray[index];

NSArray *sortedArray = [xlCollation sortedArrayFromArray:modelSection collationStringSelector:@selector(name)]; 

xlNewArray[index] = sortedPersonArrayForSection;

}

return xlNewArray;

}

返回的结果就是通过名字首字母排序并分组过的数组。。。

相关文章

网友评论

      本文标题:根据名字首字母对数组排序并分组

      本文链接:https://www.haomeiwen.com/subject/hizarttx.html