UILocalizedIndexedCollation 是相当于是tableView的一个辅助类,用来对tableView的数据源进行管理,排序,定位。brmhUILoaclizedIndexedCollation 提供了对tableView的section titles 和sectionindex titles的配置。带有section index的tableView,主要是应用于很多个分类的数据项,例如电话本,联系人的姓的首字母相同时会分在一个组下面,当联系人很多的时候,要寻找一个人就很麻烦了,这个时候边搜索的优势就体现出来了,当你点击section index 中得一个title,它就会跳到跟这个section index对应的section处。
现在我们要为tableView有个section index做准备。
1.首先创建一个UILocalizedIndexedCollation对象,它是个shared instance,所以使用
2.使用创建的theCollation调用sectionForObject:collationStringSelector:这个方法决定了每个对象属于哪个section,并返回一个NSInteger来标识这个section
for(AddressBookEntity*addressBookinaddressBookTemp){
NSIntegersect=[theCollationsectionForObject:addressBook
collationStringSelector:@selector(getFirstName)];
addressBook.sectionNumber=sect;//记录下对象的sectionid
}
其中决定对象属于哪个section是由getFirstName方法来决定的,这个方法是由自己实现的,后面我会贴出它的实现代码。当我们得到对象的section id时,我们最好记录下来,供后面获取到整个section,从而对seciton内的数据进行排序。
3.创建存储所有section的array,以及为每个section分配它的存储空间,初始空间为1。
NSIntegerhighSection=[[theCollationsectionTitles]count];
NSMutableArray*sectionArrays=[NSMutableArrayarrayWithCapacity:highSection];
for(inti=0;i<=highSection;i){
NSMutableArray*sectionArray=[NSMutableArrayarrayWithCapacity:1];
[sectionArraysaddObject:sectionArray];
}
利用数据源来填充每个section ,根据对象的section id把每个对象放入其对应的section array里
for(AddressBookEntity*addressBookinaddressBookTemp){
[(NSMutableArray*)[sectionArraysobjectAtIndex:addressBook.sectionNumber]addObject:addressBook];
}
4.用theCollation调用sortedArrayFromArray:collationStringSelector: 这个方法对每个section里面的数据进行排序,然后返回一个已经排好序的array,将其添加到一个全局变量listContent中。
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/ruanjian/article-46524-1.html