【iOS】通讯录分组方式展示数据

本文介绍如何使用Objective-C编程语言从plist文件读取医生数据,创建Doctor类进行封装,并按照姓名拼音首字母对医生进行A-Z分组显示的方法。通过实例演示了数据读取、对象创建、数据分类及表格视图展示的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本例子是将后台返回的医生列表(包含姓名和电话,demo从plist文件读取),按拼音进行分组显示(A-Z),最终效果如下图:



一、创建Doctor医生类:

Doctor类属性包括姓名、电话以及姓名第一个字的拼音首字母,同时生成初始化方法,对应的.h和.m文件如下:

JXDoctor.h

#import <Foundation/Foundation.h>

@interface JXDoctor : NSObject
#pragma mark 姓名
@property (nonatomic,copy) NSString *name;
#pragma mark 姓名拼音索引
@property (nonatomic,strong) NSString *nameIndex;
#pragma mark 电话
@property (nonatomic,copy) NSString *phoneNum;


#pragma mark 带参数的构造函数
-(JXDoctor *)initWithName:(NSString *)name andPhone:(NSString*)phone;

#pragma mark 带参数的静态对象初始化方法
+(JXDoctor *)initWithName:(NSString *)name andPhone:(NSString*)phone;

#pragma mark 根据字典初始化
+(instancetype)doctorWithDict:(NSDictionary*)dict;
-(instancetype)initWithDict:(NSDictionary*)dict;
@end

JXDoctor.m文件:

#import "JXDoctor.h"

@implementation JXDoctor
-(JXDoctor *)initWithName:(NSString *)name andPhone:(NSString*)phone{
    if(self=[super init]){
        self.name=name;
        self.phoneNum=phone;
        self.nameIndex = [self pinyinFirstLetter:name];
    }
    return self;
}

+(JXDoctor *)initWithName:(NSString *)name andPhone:(NSString*)phone{
    JXDoctor *doctor = [[JXDoctor alloc] initWithName:name andPhone:phone];
    return doctor;
}

+(instancetype)doctorWithDict:(NSDictionary*)dict{
    return [[self alloc] initWithDict:dict];
}

-(instancetype)initWithDict:(NSDictionary*)dict{
    if (self = [super init]) {
        //[self setValuesForKeysWithDictionary:dict];
        self.name = [dict objectForKey:@"name"];
        self.phoneNum = [dict objectForKey:@"phoneNum"];
        self.nameIndex = [self pinyinFirstLetter:[dict objectForKey:@"name"]];
    }
    return self;
}

//获取字符串首字母
-(NSString*)pinyinFirstLetter:(NSString*) hanzi
{
    NSString *result = @"";
    NSMutableString *ms = [[NSMutableString alloc] initWithString:hanzi];
    if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformMandarinLatin, NO)) {
//        NSLog(@"pinyin1: %@", ms);
    }
    if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformStripDiacritics, NO)){
//        NSLog(@"pinyin2: %@", ms);
    }
    if (ms.length>0) {
        result = [ms substringToIndex:1];
//        NSLog(@"pinyin3: %@", result);
    }
    return [result uppercaseString];
}
@end



二、从plist文件读取数据到doctorArr数组:

-(NSArray*)doctorArr{
    if (_doctorArr==nil) {
        NSArray *tempArr = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"doctors" ofType:@"plist"]];
        NSMutableArray *docArr = [NSMutableArray array];
        for (NSDictionary *dict in tempArr) {
            JXDoctor *doctor = [JXDoctor doctorWithDict:dict];
            [docArr addObject:doctor];
        }
        _doctorArr = docArr;
    }
    return _doctorArr;
}

*plist数据格式如下:



三、处理医生数据:

在ViewController中将从plist得到的数据转换为Doctor对象,并按照首字母进行分类,存放到

sections字典中。

-(void)setUpData{
    //创建所有的Keys
    sections = [NSMutableDictionary dictionary];
    BOOL found;
    for (JXDoctor *teamer in self.doctorArr) {
        NSString *index = teamer.nameIndex;
        found = NO;
        for(NSString *str in [sections allKeys]){
            if ([str isEqualToString:index]) {
                found = YES;
            }
        }
        //还没有对应的key,则新建
        if (!found) {
            NSLog(@"setValue:%@",index);
            [sections setValue:[[NSMutableArray alloc] init] forKey:index];
        }
    }
    //将所有Doctor数据加载进去
    for (JXDoctor *doctor in self.doctorArr)
    {
        [[sections objectForKey:doctor.nameIndex] addObject:doctor];
    }
    //按A-Z排序
    for (NSString *key in [sections allKeys])
    {
        [[sections objectForKey:key] sortUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]]];
    }
    NSLog(@"sections:%@",sections);
    [self.mainTableView reloadData];
}

四、实现UITableViewDataSource

#pragma mark - UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [[sections allKeys] count];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"%d,%d",sections.count,[[sections valueForKey:[[[sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section]] count]);
    return [[sections valueForKey:[[[sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section]] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [[[sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section];
}


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell==nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
    }
    JXDoctor *doctor = [[sections valueForKey:[[[sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
    cell.textLabel.text = doctor.name;
    cell.detailTextLabel.text = doctor.phoneNum;
    return cell;
}

//返回每组标题索引
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return [[sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
}

最后运行项目即可看到A—Z排序的效果, Demo下载:http://download.youkuaiyun.com/detail/dolacmeng/9291487






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值