應(yīng)項目需要坯墨,需添加一個自定義的通訊錄,所以需要對聯(lián)系人按名字的首字母進行排序病往。以下方法已經(jīng)封裝好捣染,復(fù)制到項目中直接可以使用。
該方法是使用UILocalizedIndexedCollation來進行本地化下按首字母分組排序的停巷,是建立在對對象的操作上的耍攘。不同于以前的那些比如把漢字轉(zhuǎn)成拼音再排序的方法了榕栏,效率不高,同時很費內(nèi)存蕾各。但該方法有一個缺點就是不能區(qū)分姓氏中的多音字扒磁,比如“曾”會被分到"C"組去。
其中參數(shù)arr是一個包含對象的數(shù)組式曲,同時對象有name屬性妨托,name屬性就是要進行分組排序的聯(lián)系人姓名,調(diào)用該方法會返回一個已經(jīng)排序好的數(shù)組吝羞,方法如下:
// 按首字母分組排序數(shù)組
-(NSMutableArray *)sortObjectsAccordingToInitialWith:(NSArray *)arr {
// 初始化UILocalizedIndexedCollation
UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
//得出collation索引的數(shù)量兰伤,這里是27個(26個字母和1個#)
NSInteger sectionTitlesCount = [[collation sectionTitles] count];
//初始化一個數(shù)組newSectionsArray用來存放最終的數(shù)據(jù),我們最終要得到的數(shù)據(jù)模型應(yīng)該形如@[@[以A開頭的數(shù)據(jù)數(shù)組], @[以B開頭的數(shù)據(jù)數(shù)組], @[以C開頭的數(shù)據(jù)數(shù)組], ... @[以#(其它)開頭的數(shù)據(jù)數(shù)組]]
NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
//初始化27個空數(shù)組加入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個數(shù)組中去
NSMutableArray *sectionNames = newSectionsArray[sectionNumber];
[sectionNames addObject:personModel];
}
//對每個section中的數(shù)組按照name屬性排序
for (NSInteger index = 0; index < sectionTitlesCount; index++) {
NSMutableArray *personArrayForSection = newSectionsArray[index];
NSArray *sortedPersonArrayForSection = [collation sortedArrayFromArray:personArrayForSection collationStringSelector:@selector(name)];
newSectionsArray[index] = sortedPersonArrayForSection;
}
// //刪除空的數(shù)組
// 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需自己定義符衔,根據(jù)項目需要來定義。