版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014128241/article/details/71600393
废话不多说上代码 直接使用该方法就可以
- (void)allDataRanger {
// 通讯录排序,分组
UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
//得出collation索引的数量,这里是27个(26个字母和1个#)
NSInteger sectionTitlesCount = [[collation sectionTitles] count];
NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
//初始化27个空数组加入newSectionsArray
for (NSInteger index = 0; index < sectionTitlesCount; index++) {
NSMutableArray *array = [[NSMutableArray alloc] init];
[newSectionsArray addObject:array];
}
//将每个人按name分到某个section下 _dataSource存储的是模型数组
for (WDCar *model in _dataSource) {
//获取name属性的值所在的位置,比如"林丹",首字母是L,在A~Z中排第11(第一位是0),sectionNumber就为11
NSInteger sectionNumber = [collation sectionForObject:model collationStringSelector:@selector(name)];
//把name为“林丹”的p加入newSectionsArray中的第11个数组中去
NSMutableArray *sectionNames = newSectionsArray[sectionNumber];
[sectionNames addObject:model];
}
//对每个section中的数组按照name属性排序
for (NSInteger index = 0; index < sectionTitlesCount; index++) {
NSMutableArray *personArrayForSection = newSectionsArray[index];
NSArray *sortedPersonArrayForSection = [collation sortedArrayFromArray:personArrayForSection collationStringSelector:@selector(name)];
newSectionsArray[index] = sortedPersonArrayForSection;
}
//将排序好的通讯录名单存到数据库里面 _indexDataSource存储的是计算出来的字母
// [messageDbManger saveUserToDataBase:_allDataSource];
NSMutableArray *temp = [NSMutableArray new];
_indexDataSource = [NSMutableArray new];
[newSectionsArray enumerateObjectsUsingBlock:^(NSArray *arr, NSUInteger idx, BOOL *stop) {
if (arr.count == 0) {
[temp addObject:arr];
} else {
[_indexDataSource addObject:[collation sectionTitles][idx]];
}
}];
// 存储的是每个字母下面的模型数组
_allDataSource =[[NSMutableArray alloc]init];
[newSectionsArray removeObjectsInArray:temp];
[_allDataSource removeAllObjects];
[_allDataSource addObjectsFromArray:newSectionsArray];