iOS - 通訊錄開發,名字按拼音首字母分組排序

應項目需要,需添加一個自定義的通訊錄,所以需要對聯系人按名字的首字母進行排序。以下方法已經封裝好,復制到項目中直接可以使用。
該方法是使用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需自己定義,根據項目需要來定義。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 第5章 引用類型(返回首頁) 本章內容 使用對象 創建并操作數組 理解基本的JavaScript類型 使用基本類型...
    大學一百閱讀 3,270評論 0 4
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,779評論 18 399
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,993評論 19 139
  • “那個呀,那是慕容家培養出來的海棠花,名叫異香海棠” “你拾到那枝花應該是你的那位‘同窗’掉下來的噢” “先生,你...
    蘇沐楊閱讀 598評論 0 0
  • 1,如何有效的利用搜索引擎。很多人打開瀏覽器的第一件事兒,就是百度、谷歌,但是真正知道有效利用搜索引擎的不多。推薦...
    維度空間閱讀 6,872評論 0 10