// // ViewController.m // 06-UITableView02-单组数据 #import "ViewController.h" #import "XMGHero.h" @interface ViewController () <UITableViewDataSource> /** 英雄数据 */ @property (nonatomic, strong) NSArray *heroes; @end @implementation ViewController - (NSArray *)heroes { if (_heroes == nil) { // 加载plist中的字典数组 NSString *path = [[NSBundle mainBundle] pathForResource:@"heroes.plist" ofType:nil]; NSArray *dictArray = [NSArray arrayWithContentsOfFile:path]; // 字典数组 -> 模型数组 NSMutableArray *heroArray = [NSMutableArray array]; for (NSDictionary *dict in dictArray) { XMGHero *hero = [XMGHero heroWithDict:dict]; [heroArray addObject:hero]; } _heroes = heroArray; } return _heroes; } - (void)viewDidLoad { [super viewDidLoad]; } #pragma mark - <UITableViewDataSource> // 默认就是1组 //- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView //{ // return 1; //} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.heroes.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil]; XMGHero *hero = self.heroes[indexPath.row]; cell.textLabel.text = hero.name; cell.imageView.image = [UIImage imageNamed:hero.icon]; cell.detailTextLabel.text = hero.intro; return cell; } @end
// // XMGHero.h // 06-UITableView02-单组数据 #import <Foundation/Foundation.h> @interface XMGHero : NSObject /** 姓名 */ @property (nonatomic, strong) NSString *name; /** 图标 */ @property (nonatomic, strong) NSString *icon; /** 简介 */ @property (nonatomic, strong) NSString *intro; + (instancetype)heroWithDict:(NSDictionary *)dict; @end
// // XMGHero.m // 06-UITableView02-单组数据 #import "XMGHero.h" @implementation XMGHero + (instancetype)heroWithDict:(NSDictionary *)dict { XMGHero *hero = [[self alloc] init]; // hero.name = dict[@"name"]; // hero.icon = dict[@"icon"]; // hero.intro = dict[@"intro"]; [hero setValuesForKeysWithDictionary:dict]; return hero; } @end
时间: 2024-11-06 09:59:39