SDK里已经提供了一个实现此功能的神器——UILocalizedIndexedCollation。
首先提一下,UILocalizedIndexedCollation的分组排序是建立在对对象的操作上的。下边举个列子讲解一下。首先已知有一个Person类:
1 @interface Person : NSObject 2 @property(nonatomic, strong) NSString *name; 3 @end然后初始化一些对象存入一个数组( 注:为了后续说明方便,我直接拿name的值来表示Person类的对象,实际编码中是要用对象!如下列<林丹>表示p.name = @"林丹"的Person类对象p )
1 NSArray *srcArray = @[<林荣>, <林丹>, <周董>, <周树人>, <周杰伦>, <阿华>];先将UILocalizedIndexedCollation初始化,
1 UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];可以看出来这是一个单例,它会根据不同国家的语言初始化出不同的结果。如中文和英文的得到的就是A~Z和#,日语的就是A~Z,あ, か, さ, た, な, は, ま, や, ら, わ和#。下边我就以最熟悉的中文环境为例,直接上代码了,注意看注释部分的讲解
1 //得出collation索引的数量,这里是27个(26个字母和1个#) 2 NSInteger sectionTitlesCount = [[collation sectionTitles] count]; 3 4 //初始化一个数组newSectionsArray用来存放最终的数据,我们最终要得到的数据模型应该形如@[@[以A开头的数据数组], @[以B开头的数据数组], @[以C开头的数据数组], ... @[以#(其它)开头的数据数组]] 5 6 NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount]; 7 8 //初始化27个空数组加入newSectionsArray 9 for (NSInteger index = 0; index < sectionTitlesCount; index++) { 10 NSMutableArray *array = [[NSMutableArray alloc] init]; 11 [newSectionsArray addObject:array]; 12 } 13 14 //将每个人按name分到某个section下 15 16 for (Person *p in srcArray) { 17 //获取name属性的值所在的位置,比如"林丹",首字母是L,在A~Z中排第11(第一位是0),sectionNumber就为11 18 NSInteger sectionNumber = [collation sectionForObject:p collationStringSelector:@selector(name)]; 19 //把name为“林丹”的p加入newSectionsArray中的第11个数组中去 20 NSMutableArray *sectionNames = newSectionsArray[sectionNumber]; 21 [sectionNames addObject:p]; 22 } 23 24 //对每个section中的数组按照name属性排序 25 for (NSIntger index = 0; index < sectionTitlesCount; index++) { 26 NSMutableArray *personArrayForSection = newSectionsArray[index]; 27 NSArray *sortedPersonArrayForSection = [collation sortedArrayFromArray:personArrayForSection collationStringSelector:@selector(name)]; 28 newSectionsArray[index] = sortedPersonArrayForSection; 29 }最终把newSectionsArray应该形如@[@[<阿华>], @[], @[], ... @[<林丹>, <林荣>], ... @[], @[<周董>, <周杰伦>, <周树人>]]
后续工作就是把这个数组作为数据源与UITableView通过tableView的Delegate关联起来了,部分如下,在此不再赘述
1 - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 2 return [collation sectionTitles][section]; 3 } 4 5 - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { 6 return [collation sectionIndexTitles]; 7 } 8 9 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { 10 return [collation sectionForSectionIndexTitleAtIndex:index]; 11 }不过呢,使用这个UILocalizedIndexedCollation有一个缺点就是不能区分姓氏中的多音字,比如“曾”会被分到"C"组去,不知道大家有没有基于此的好方法在下边回复。下边是苹果官方示例,其中第3个是关于UILocalizedIndexedCollation的,可以下载下来学习一下 http://developer.apple.com/library/ios/samplecode/TableViewSuite/Introduction/Intro.html