// CZGroup.h
// UITableView02
//
// Created by qi tan on 2023/5/29.
//
#import <Foundation/Foundation.h>
@interface CZGroup : NSObject
@property(nonatomic,copy)NSString *title;
@property(nonatomic,copy)NSString *desc;
@property(nonatomic,strong)NSArray *cars;
-(instancetype)initWithDict:(NSDictionary *)dict;
+(instancetype)groupWithDict:(NSDictionary *)dict;
@end
//
// CZGroup.m
// UITableView02
// Created by qi tan on 2023/5/29.
#import "CZGroup.h"
@implementation CZGroup
- (instancetype)initWithDict:(NSDictionary *)dict
{
if(self = [super init]) {
// self.title = dict[@"title"];
// KVC
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
+(instancetype)groupWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}
@end
//
// ViewController.m
// UITableView02
//
// Created by qi tan on 2023/5/29.
//
#import "ViewController.h"
#import "CZGroup.h"
@interface ViewController () <UITableViewDataSource>
@property(nonatomic,strong)NSArray *groups; // 数据源
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@end
@implementation ViewController
#pragma mark - 懒加载数据
-(NSArray *)groups
{
if(_groups == nil){
NSString *path = [[NSBundle mainBundle] pathForResource:@"cars_simple.plist" ofType:nil];
NSArray *arrayDict = [NSArray arrayWithContentsOfFile:path] ;
NSMutableArray * arrayM = [NSMutableArray array];
for (NSDictionary* dict in arrayDict) {
CZGroup *model = [CZGroup groupWithDict:dict];
[arrayM addObject:model];
}
_groups = arrayM;
}
return _groups;
}
#pragma mark - 数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.groups.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
CZGroup *group = self.groups[section];
return group.cars.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CZGroup *group = self.groups[indexPath.section];
NSString *name = group.cars[indexPath.row];
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:nil];
cell.textLabel.text = name;
return cell;
}
#pragma mark - 分组信息的方法
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
CZGroup *group = self.groups[section];
return group.title;
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
CZGroup *group = self.groups[section];
return group.desc;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.dataSource = self;
}
@end