关键字:字母表,按首字母排序,索引表
遇到开发好友列表,产品要求好友列表按字母排序,本人刚参与工作,只能google或者百度,借鉴大神。结果搜到的是一堆第三方框架,大神的轮子,然而这并不是我想要的,只能翻一下苹果官方文档,不负有心人,找到了神器UILocalizedIndexedCollation。
1、理论
-
获取单例 currentCollation
-
分组排序
- sectionForObject:collationStringSelector: - 指定对象的某个属性,获取该对象对应分类到的section的section Number(决定了每个对象属于哪个section,并返回一个NSInteger值来标识这个section)
- sortedArrayFromArray:collationStringSelector: - 指定对象的某个属性,并传入数组,对数组排序 -
为tableview提供数据
sectionTitles - 获取当前地区区域header标题数组
sectionIndexTitles - 获取当前地区区域索引标题数组
- sectionForSectionIndexTitleAtIndex: - 返回当用户触摸到某个索引标题时列表应该跳至的区域的索引。
注:section title 和section index title 是可以不相同的。
2、实战
接下来就讲讲它的具体使用,三部曲:
- 1、获取单例的collation
- 2、分组(分类)
- 3、排序
1、获取单例的collation
UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
//标题数组
NSInteger sectionTitlesCount = [[collation sectionTitles] count];
//设置sections数组初始化:元素包含userObjs数据的空数据
NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
for (NSInteger index = 0; index < sectionTitlesCount; index++) {
NSMutableArray *array = [[NSMutableArray alloc] init];
[newSectionsArray addObject:array];
}
2、分类 - 将用户数据进行分类,存储到对应的sesion数组中
for (MTDUserBaseModel *p in self.friendListRequest.friendMutableArray) {
NSInteger sectionNumber = [collation sectionForObject:p collationStringSelector:@selector(userNickname)];
NSMutableArray *sectionNames = newSectionsArray[sectionNumber];
[sectionNames addObject:p];
}
3、排序 - 对每个已经分类的数组中的数据进行排序
for (NSInteger index = 0; index < sectionTitlesCount; index++) {
NSMutableArray *personArrayForSection = newSectionsArray[index];
NSArray *sortedPersonArrayForSection = [collation sortedArrayFromArray:personArrayForSection collationStringSelector:@selector(userNickname)];
newSectionsArray[index] = sortedPersonArrayForSection;
}
参考:
1、苹果示例代码
2、UILocalizedIndexedCollation
网友评论