标签:
//获取字符串(或者汉字)的首字母
-(NSString*)firstCharacterWithString:(NSString *)string
{
NSMutableString *str = [NSMutableString stringWithString:string];
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
NSString *pingyin = [str capitalizedString];
return [pingyin substringFromIndex:1];
}
//将字符串属猪按照元素首字母进行排序分组
-(NSDictionary *)dictonaryOrderByCharaterWithOriginalArray:(NSArray *)array
{
if (array.count == 0) {
return nil;
}
for (id obj in array) {
if (![obj isKindOfClass:[NSString class]]) {
return nil;
}
}
UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation currentCollation];
NSMutableArray *objects =[NSMutableArray arrayWithCapacity:indexedCollation.sectionTitles.count];
for (int i = 0; i < indexedCollation.sectionTitles.count; i++) {
NSMutableArray *array = [NSMutableArray array];
[objects addObject:array];
}
NSMutableArray *keys = [NSMutableArray arrayWithCapacity:objects.count];
//按字母顺序分组
NSInteger lastIndex = -1;
for (int i = 0; i < array.count; i ++) {
NSInteger index = [indexedCollation sectionForObject:array[i] collationStringSelector:@selector(uppercaseString)];
[[objects objectAtIndex:index]addObject:array[i]];
lastIndex = index;
}
//去掉空数组
for (int i = 0; i<objects.count; i++) {
NSMutableArray *obj = objects[i];
if (obj.count == 0) {
[objects removeObject:obj];
}
}
//获取索引字母
for (NSMutableArray *obj in objects) {
NSString *str = obj[0];
NSString *key = [self firstCharacterWithString:str];
[keys addObject:key];
}
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setObject:objects forKey:keys];
return dic;
}
标签:
原文地址:http://www.cnblogs.com/PJXWang/p/5614832.html