通讯录

本文介绍了一个使用Objective-C实现的通讯录管理应用,详细解释了如何通过字典和数组结构存储联系人信息,并利用UITableView进行高效的数据展示。代码中包括了联系人数据的加载、排序和分组,以及单元格的定制化显示。
#import "ContactViewController.h"
//通讯录: 最外面是字典, key(A,B,C...) - keyArray ; value(数组(image1,name1; image2, name2; ...), 可见每个元素都是字典)
@interface ContactViewController ()<UITableViewDataSource>
@property (nonatomic, copy)NSDictionary *contactDic;
@property (nonatomic, copy)NSArray *keyArray;//装key 值的数组
@end

static NSString *identifier = @"abc";
@implementation ContactViewController

- (void)dealloc
{
    [_keyArray release];
    [_contactDic release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    UITableView *tabView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    [self.view addSubview:tabView];
    tabView.dataSource = self;
    [tabView registerClass:[UITableViewCell class] forCellReuseIdentifier:identifier];
    [tabView release];

    NSString *path = [[NSBundle mainBundle] pathForResource:@"Contact" ofType:@"plist"];
    self.contactDic = [NSDictionary dictionaryWithContentsOfFile:path];
    //数组排序(A, B, C, D...)
    self.keyArray = [self.contactDic.allKeys sortedArrayUsingSelector:@selector(compare:)];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource
//多少分区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.keyArray.count;
}

//多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *key = self.keyArray[section];
    NSArray *array = self.contactDic[key];
    return array.count;
}

//单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];

    NSString *key = self.keyArray[indexPath.section];//获取到 key 值
    NSArray *array = self.contactDic[key];// 根据 key 值, 找到数组

    //数组的 key, 数组的 value
    NSDictionary *dic = array[indexPath.row];//数组里面的具体某个元素
    cell.imageView.image = [UIImage imageNamed:dic[@"image"]];
    cell.textLabel.text = dic[@"name"];

    return cell;
}

//分区数组
- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return self.keyArray[section];
}

//右边的
- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView  {
    return self.keyArray;
}

@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值