在oc開發中,請求下來的數據大多數是無規則的,但是boss要求要排序并且加上索引,這樣用戶就可以在大量的數組中準確的定位到自己所要找的內容,然而很多初學者對oc中封裝的類不是很了解,所以用大篇幅的代碼來做判斷,整理數組。
在這,給大家發一個小Demo,希望對大家有所幫助,同時,有錯誤的地方希望大大們批評指教。
#pragma mark-通過名稱首字母給對象排序并分組。(這段代碼可以直接復制粘貼進自己的工程)
-(NSMutableArray *)sortObjectsAccordingToInitialWith:(NSArray *)arr {
//初始化UILocalizedIndexedCollation
UILocalizedIndexedCollation *xlCollation = [UILocalizedIndexedCollation currentCollation];
//得出collation索引的數量
NSInteger xlTitlesCount = [[xlCollation sectionTitles]count];
//數組xlNewArray用來存放最終的數據
NSMutableArray *xlNewArray = [[NSMutableArray alloc]initWithCapacity:xlTitlesCount];
//初始化27個空數組加入newSectionsArray( 26個英文字母加一個#號)
for(NSInteger i = 0; i < xlTitlesCount; i++) {
NSMutableArray *array = [[NSMutableArray alloc]init];
[xlNewArray addObject:array];
}
//將每個名字分到某個section下(CarTypeModel是你創建的model)
for(CarTypeModel *Model in _carProductArray) {
//獲取name屬性的值所在的位置
NSInteger section = [xlCollation sectionForObject:Model collationStringSelector:@selector(name)];
//通過name把對應的Model放到對應的section中。
NSMutableArray *sectionNames = xlNewArray[section];
[sectionNames addObject:Model];
}
//對每個section中的數組按照name屬性排序
for(NSInteger i =0; i < xlTitlesCount; i++) {
NSMutableArray *modelSection = xlNewArray[index];
NSArray *sortedArray = [xlCollation sortedArrayFromArray:modelSection collationStringSelector:@selector(name)];?
xlNewArray[index] = sortedPersonArrayForSection;
}
return xlNewArray;
}
返回的結果就是通過名字首字母排序并分組過的數組。。。