應項目需要,需添加一個自定義的通訊錄,所以需要對聯系人按名字的首字母進行排序。以下方法已經封裝好,復制到項目中直接可以使用。
該方法是使用UILocalizedIndexedCollation來進行本地化下按首字母分組排序的,是建立在對對象的操作上的。不同于以前的那些比如把漢字轉成拼音再排序的方法了,效率不高,同時很費內存。但該方法有一個缺點就是不能區分姓氏中的多音字,比如“曾”會被分到"C"組去。
其中參數arr是一個包含對象的數組,同時對象有name屬性,name屬性就是要進行分組排序的聯系人姓名,調用該方法會返回一個已經排序好的數組,方法如下:
// 按首字母分組排序數組
-(NSMutableArray *)sortObjectsAccordingToInitialWith:(NSArray *)arr {
// 初始化UILocalizedIndexedCollation
UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
//得出collation索引的數量,這里是27個(26個字母和1個#)
NSInteger sectionTitlesCount = [[collation sectionTitles] count];
//初始化一個數組newSectionsArray用來存放最終的數據,我們最終要得到的數據模型應該形如@[@[以A開頭的數據數組], @[以B開頭的數據數組], @[以C開頭的數據數組], ... @[以#(其它)開頭的數據數組]]
NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
//初始化27個空數組加入newSectionsArray
for (NSInteger index = 0; index < sectionTitlesCount; index++) {
NSMutableArray *array = [[NSMutableArray alloc] init];
[newSectionsArray addObject:array];
}
//將每個名字分到某個section下
for (PersonModel *personModel in _contactsArr) {
//獲取name屬性的值所在的位置,比如"林丹",首字母是L,在A~Z中排第11(第一位是0),sectionNumber就為11
NSInteger sectionNumber = [collation sectionForObject:personModel collationStringSelector:@selector(name)];
//把name為“林丹”的p加入newSectionsArray中的第11個數組中去
NSMutableArray *sectionNames = newSectionsArray[sectionNumber];
[sectionNames addObject:personModel];
}
//對每個section中的數組按照name屬性排序
for (NSInteger index = 0; index < sectionTitlesCount; index++) {
NSMutableArray *personArrayForSection = newSectionsArray[index];
NSArray *sortedPersonArrayForSection = [collation sortedArrayFromArray:personArrayForSection collationStringSelector:@selector(name)];
newSectionsArray[index] = sortedPersonArrayForSection;
}
// //刪除空的數組
// NSMutableArray *finalArr = [NSMutableArray new];
// for (NSInteger index = 0; index < sectionTitlesCount; index++) {
// if (((NSMutableArray *)(newSectionsArray[index])).count != 0) {
// [finalArr addObject:newSectionsArray[index]];
// }
// }
// return finalArr;
return newSectionsArray;
}
其中的PersonModel需自己定義,根據項目需要來定義。