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需自己定义,根据项目需要来定义。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值