###################### 测试代码 ##########################
NSArray *sortArray = @[@"du",@"zhong",@"dulibai",@"shu",@"杜树忠"];
NSMutableArray *userModels = [NSMutableArray array];
for (NSString *name in sortArray) {
// User *user = [User new];
// user.name = name;
[userModels addObject:name];
}
NSMutableArray *list = [self sortArray:sortArray];
//NSArray *sortedArray = [userModels sortedArrayUsingFunction:nickNameSort context:NULL];
// for (User *user in sortedArray) {
// NSLog(@"%@",user.name);
// }
for (NSString *user in list) {
NSLog(@"%@",user);
}
############### 功能代码 ###################
-
(NSMutableArray*)sortArray:(NSArray *)toSortArray{
//将传入数组转换为可变数组
NSMutableArray *needSortArray = [NSMutableArray arrayWithArray:toSortArray];
//存储对应字母开头的所有数据的数组
NSMutableArray *classifiedArray = [[NSMutableArray alloc] init];for(int i='A';i<='Z';i++){
NSMutableArray *rulesArray = [[NSMutableArray alloc] init];
NSString *indexString = [NSString stringWithFormat:@"%c",i];
for(int j = 0; j < needSortArray.count; j++){
User *model = [needSortArray objectAtIndex:j];
//NSString *model = [needSortArray objectAtIndex:j];if([[self toPinyin: model] isEqualToString:indexString]){ //把model.name首字母相同的放到同一个数组里面 [rulesArray addObject:model]; [needSortArray removeObject:model]; j--; } } if (rulesArray.count !=0) { [classifiedArray addObject:rulesArray]; } if (needSortArray.count == 0) { break; }
}
// 剩下的就是非字母开头数据,加在classifiedArray的后面
if (needSortArray.count !=0) {
[classifiedArray addObject:needSortArray];
}//最后再分别对每个数组排序
NSMutableArray *sortCompleteArray = [NSMutableArray array];
for (NSArray *tempArray in classifiedArray) {
NSArray *sortedElement = [tempArray sortedArrayUsingFunction:nickNameSort context:NULL];
[sortCompleteArray addObject:sortedElement];
}
//sortCompleteArray就是最后排好序的二维数组了
return sortCompleteArray;
}
- (NSString *)toPinyin:(NSString *)str{
NSMutableString *ms = [[NSMutableString alloc]initWithString:str];
if (CFStringTransform((__bridge CFMutableStringRef)ms, 0,kCFStringTransformMandarinLatin, NO)) {
}
// 去除拼音的音调
if (CFStringTransform((__bridge CFMutableStringRef)ms, 0,kCFStringTransformStripDiacritics, NO)) {
if (str.length) {
NSString *bigStr = [ms uppercaseString];
NSString *cha = [bigStr substringToIndex:1];
return cha;
}
}
return str;
}
网友评论