#import "AnimalViewController.h"
//引入 plist 文件, 动物的通讯录(最外层是字典, key 是(A,B,C, D, E, F, ...Z); value(里面是数组, 每个 key 值, 对应的都是一个数组, 数组里面都是字符串))
//注: keyArray 数组, 字母的排序, 数组
@interface AnimalViewController () <UITableViewDataSource>
//通讯录: 最外层是字典, key(A, B, C...Z), value(里面放的是数组-存放一个个字符串(动物的名字))
@property (nonatomic, copy)NSDictionary *animalDic; //字典, NSDictionary, 遵守 NSCopy 协议
@property (nonatomic, copy)NSArray *keyArray; //数组, 字母的排序, 数组
@end
static NSString *identifier = @"abc";//设置全局的, 防止写错
@implementation AnimalViewController
- (void)dealloc
{
[_animalDic release];
[_keyArray release];
[super dealloc];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
UITableView *tabelVC = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
tabelVC.dataSource = self;
[tabelVC registerClass:[UITableViewCell class] forCellReuseIdentifier:identifier];
[self.view addSubview:tabelVC];
[tabelVC release];
//因为 字典中, 数据无序; 为了让从 A- Z; 建立了 Animal文件资源,, 获取文件资源
NSString *path = [[NSBundle mainBundle] pathForResource:@"Animal" ofType:@"plist"];
self.animalDic = [NSDictionary dictionaryWithContentsOfFile:path];//外层是字典
//因为字典无序, 所以, 将 key 全都取出来, 按照顺序放入数组中
self.keyArray = [self.animalDic.allKeys sortedArrayUsingSelector:@selector(compare:)];// compare:方法, 从小到大排序; keyArray, 里面
NSLog(@"%@", self.animalDic);
NSLog(@"%@", self.keyArray);
}
- (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 {
//当前是哪个分区, 比如 A 分区, section 是行数,
NSString *key = self.keyArray[section];
//找到 A 对应的数组
NSArray *array = self.animalDic[key];//A 对应的是一个数组 array
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.animalDic[key];//通过 key 值, 找数组
NSString *animalName = array[indexPath.row];//数组里面就是 name
cell.textLabel.text = animalName;
return cell;
}
//分区头标
- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return self.keyArray[section];
}
//右边的效果
- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return self.keyArray;
}
@end
动物按姓名排名
最新推荐文章于 2024-09-17 01:05:45 发布