UILocalizedIndexedCollation 可以对数组重建索引,按照首字母顺序进行排序。
LCIndexTool.h
#define kToolsIndexAryKey @"LCIndexAryKey" //索引
#define kToolsGroupAryKey @"LCGroupAryKey" //排序后的分组
/**
对数组排序
@param mArray 需要排序的数组
@param proretyName 数组中对象需要排序的属性
@return 排序后的索引及gourpAry 字典形式 kToolsIndexAryKey kToolsGroupAryKey
*/
+ (NSDictionary *)sortedArrayWithChineseObject:(NSMutableArray *)mArray withPropertyNameSEL:(SEL)nameSEL ;
proretyName为属性名称例如:
Person 类 属性 :name age phoneNumber
我们需要根据name的首字母来排序分组 则传递@selector(name)
LCIndexTool.m
//数组排序
+ (NSDictionary *)sortedArrayWithChineseObject:(NSMutableArray *)mArray withPropertyNameSEL:(SEL)nameSEL {
UILocalizedIndexedCollation *indexCollation = [UILocalizedIndexedCollation currentCollation];
NSInteger index, sectionTitlesCount = [[indexCollation sectionTitles] count];
NSMutableArray *suoYinArr = [[NSMutableArray alloc] initWithArray:[indexCollation sectionTitles]];
//临时数据,存放section对应的userObjs数组数据
NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
//设置sections数组初始化:元素包含userObjs数据的空数据
for (index = 0; index < sectionTitlesCount; index++) {
NSMutableArray *array = [[NSMutableArray alloc] init];
[newSectionsArray addObject:array];
}
//分组
for (id object in mArray) {
//根据timezone的localename,获得对应的的section number
NSInteger sectionNumber = [indexCollation sectionForObject:object collationStringSelector:nameSEL];
//根据sectionNumber获取数组
NSMutableArray *sectionUserObjs = [newSectionsArray objectAtIndex:sectionNumber];
//添加对象到对应的数组中
[sectionUserObjs addObject:object];
}
//获取空的数组的index
NSMutableArray *willDeleteAry = [NSMutableArray new];
for (int i = 0; i < newSectionsArray.count; i ++) {
NSArray *tempAry = newSectionsArray[i];
if (tempAry.count == 0) {
[willDeleteAry addObject:[NSString stringWithFormat:@"%d",i]];
}
}
//删除空的数组
for (NSInteger i = willDeleteAry.count; i > 0; i -- ) {
NSInteger index = [willDeleteAry[i - 1] integerValue];
[newSectionsArray removeObjectAtIndex:index];
[suoYinArr removeObjectAtIndex:index];
}
//该字典中存放分组排序呢后的索引及数据
NSDictionary *dict = @{kToolsGroupAryKey:newSectionsArray,kToolsIndexAryKey:suoYinArr};
return dict;
}
网友评论