iOS 根据通讯录首字母排序

2022-10-13  本文已影响0人  肉肉要次肉

新建继承NSObject的文件,取名为LinkManSort

LinkManSort.m文件

#import "LinkManSort.h"

staticNSString*constCYPinyinGroupResultArray =@"CYPinyinGroupResultArray";

staticNSString*constCYPinyinGroupCharArray =@"CYPinyinGroupCharArray";

@implementation LinkManSort

// 按首字母分组排序数组

+ (NSDictionary *)sortObjectsAccordingToInitialWith:(NSArray *)willSortArr SortKey:(NSString *)sortkey {

    // 初始化UILocalizedIndexedCollation

    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];

    // 得出collation索引的数量,这里是27个(26个字母和1个#)

    NSIntegersectionTitlesCount = [[collationsectionTitles]count];

    // 初始化一个数组newSectionsArray用来存放最终的数据,我们最终要得到的数据模型应该形如

    // @[@[以A开头的数据数组], @[以B开头的数据数组], @[以C开头的数据数组], ... @[以#(其它)开头的数据数组]]

    NSMutableArray*newSectionsArray = [[NSMutableArrayalloc]initWithCapacity:sectionTitlesCount];

    //初始化27个空数组加入newSectionsArray

    for(NSIntegerindex =0; index < sectionTitlesCount; index++) {

        NSMutableArray *array = [[NSMutableArray alloc] init];

        [newSectionsArrayaddObject:array];

    }

    NSLog(@"newSectionsArray %@ %@",newSectionsArray,collation.sectionTitles);

    NSMutableArray *firstChar = [NSMutableArray arrayWithCapacity:10];

    //将每个名字分到某个section下

    for(idModelinwillSortArr) {

        //获取name属性的值所在的位置,比如"林丹",首字母是L,在A~Z中排第11(第一位是0),sectionNumber就为11

        NSInteger sectionNumber = [collation sectionForObject:Model collationStringSelector:NSSelectorFromString(sortkey)];

        //把name为“林丹”的p加入newSectionsArray中的第11个数组中去

        NSMutableArray*sectionNames = newSectionsArray[sectionNumber];

        [sectionNamesaddObject:Model];

        //拿出每名字的首字母

        NSString* str= collation.sectionTitles[sectionNumber];

        [firstCharaddObject:str];

        NSLog(@"sectionNumbersectionNumber %ld %@",sectionNumber,str);

    }

    //返回首字母排好序的数据

    NSArray*firstCharResult = [selfSortFirstChar:firstChar];

    NSLog(@"firstCharResult== %@",firstCharResult);

    //对每个section中的数组按照name属性排序

    for(NSIntegerindex =0; index < sectionTitlesCount; index++) {

        NSMutableArray*personArrayForSection = newSectionsArray[index];

        NSArray*sortedPersonArrayForSection = [collationsortedArrayFromArray:personArrayForSectioncollationStringSelector:@selector(name)];

        newSectionsArray[index] = sortedPersonArrayForSection;

    }

    //删除空的数组

    NSMutableArray *finalArr = [NSMutableArray new];

    for(NSIntegerindex =0; index < sectionTitlesCount; index++) {

        if(((NSMutableArray*)(newSectionsArray[index])).count!=0) {

            [finalArraddObject:newSectionsArray[index]];

        }

    }

    return @{CYPinyinGroupResultArray:finalArr,CYPinyinGroupCharArray:firstCharResult};

}

+ (NSArray*)SortFirstChar:(NSArray*)firstChararry

{

    //数组去重复

    NSMutableArray *noRepeat = [[NSMutableArray alloc]initWithCapacity:8];

    NSMutableSet*set = [[NSMutableSetalloc]initWithArray:firstChararry];

    [setenumerateObjectsUsingBlock:^(idobj ,BOOL*stop){

        [noRepeataddObject:obj];

    }];

    //字母排序

    NSArray*resultkArrSort1 = [noRepeatsortedArrayUsingComparator:^NSComparisonResult(idobj1,idobj2) {

        return [obj1 compare:obj2 options:NSNumericSearch];

    }];

    //把”#“放在最后一位

    NSMutableArray*resultkArrSort2 = [[NSMutableArrayalloc]initWithArray:resultkArrSort1];

    if([resultkArrSort2containsObject:@"#"]) {

        [resultkArrSort2removeObject:@"#"];

        [resultkArrSort2addObject:@"#"];

    }

    returnresultkArrSort2;

}

@end

LinkManSort.h文件

重点是,记得要引入UIKit头文件 #import <UIKit/UIKit.h>

不然UILocalizedIndexedCollation会报错

+ (NSDictionary *)sortObjectsAccordingToInitialWith:(NSArray *)willSortArr SortKey:(NSString *)sortkey;

创建model

-----PersonModel.h

NS_ASSUME_NONNULL_BEGIN

@interface PersonModel : NSObject

@property(nonatomic, strong) NSString *name;

- (instancetype)initWithName:(NSString*)name;

@end

-----PersonModel.m

#import "PersonModel.h"

@implementation PersonModel

- (instancetype)initWithName:(NSString*)name {

    if(self= [superinit]) {

        self.name= name;

    }

    return self;

}

@end

调用方法,引入头文件#import "LinkManSort.h"

#import "ViewController.h"

#import "PersonModel.h"

#import "LinkManSort.h"

staticNSString*constCYPinyinGroupResultArray =@"CYPinyinGroupResultArray";

staticNSString*constCYPinyinGroupCharArray =@"CYPinyinGroupCharArray";

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)NSArray *dataSource;

@property(nonatomic,strong)UILocalizedIndexedCollation *collation;

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *sectionArr;//分区数组

@property(nonatomic,strong)NSMutableArray *indexArr;//索引数组

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    self.sectionArr = [NSMutableArray array];

    [self.view addSubview:self.tableView];

    [selfloadData];

}

#pragma mark - UITableViewDataSource

- (NSString*)tableView:(UITableView*)tableViewtitleForHeaderInSection:(NSInteger)section {

    returnself.indexArr[section];

}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {

    return [self.collation sectionIndexTitles];

}

//索引列点击事件

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {

    return [self.collation sectionForSectionIndexTitleAtIndex:index];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return self.indexArr.count;

}

- (NSInteger)tableView:(UITableView*)tableViewnumberOfRowsInSection:(NSInteger)section {

    return[self.dataSource[section]count];

}

- (UITableViewCell*)tableView:(UITableView*)tableViewcellForRowAtIndexPath:(NSIndexPath*)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class]) forIndexPath:indexPath];

    PersonModel*person = [self.dataSource[indexPath.section]objectAtIndex:indexPath.row];

    cell.textLabel.text= person.name;

    returncell;

}

- (UITableView *)tableView {

    if(_tableView==nil) {

        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) style:UITableViewStylePlain];

        _tableView.delegate=self;

        _tableView.backgroundColor = [UIColor lightGrayColor];

        _tableView.dataSource=self;

        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];

    }

    return _tableView;

}

//数据源

- (void)loadData {

    NSArray *testArr = @[@"杨幂",@"李易峰",@"王祖蓝", @"垃圾", @"苏有朋", @"大海", @"佟丽娅", @"霍建华", @"薛之谦", @"周笔畅", @"李宇春", @"张靓颖", @"阿里郎", @"胡一天", @"贾乃亮", @"罗晋",@"~~肉肉~~"];

    NSMutableArray*personArr = [NSMutableArrayarrayWithCapacity:testArr.count];

    for(NSString*strintestArr) {

        //排序str

        PersonModel*person = [[PersonModelalloc]initWithName:str];

        [personArraddObject:person];

    }

    NSDictionary *dcit= [LinkManSort sortObjectsAccordingToInitialWith:personArr SortKey:@"name"];

    self.dataSource = dcit[CYPinyinGroupResultArray];//排好顺序的PersonModel数组

    self.indexArr = dcit[CYPinyinGroupCharArray];//排好顺序的首字母数组

    self.collation = [UILocalizedIndexedCollation currentCollation];

}

上一篇 下一篇

猜你喜欢

热点阅读