您的位置:首页 > 编程语言

一个简单的类似通讯录的封装代码

2017-05-11 08:59 423 查看

废话不多说上代码 直接使用该方法就可以

- (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:pe
abfa
rsonArrayForSection 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];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  class 索引 通讯录