英雄列表小应用的流程

1、通过plist加载模型对象,代码如下:

#import <Foundation/Foundation.h>

 

@interface CZHero : NSObject

@property (nonatomic,copy) NSString *name ;

@property (nonatomic,copy) NSString *intro ;

@property (nonatomic,copy) NSString *icon ;

-  (instancetype) initWithDic:(NSDictionary *)dic;

+ (instancetype) heroWithDic:(NSDictionary *)dic;

+ (NSArray *)heroList;

 @end

#import "CZHero.h"

 @implementation CZHero

-  (instancetype) initWithDic:(NSDictionary *)dic

{

    if (self == [super init]) {

        [self setValuesForKeysWithDictionary:dic];

    }

    return self;

}

+ (instancetype) heroWithDic:(NSDictionary *)dic

{

    return  [[self alloc] initWithDic:dic];

}

+ (NSArray *)heroList

{

    NSString *path = [[NSBundle mainBundle ] pathForResource:@"heros" ofType:@"plist"];

    NSArray *dicArray = [NSArray arrayWithContentsOfFile:path];

    NSMutableArray *tmpArray = [NSMutableArray array];

    for (NSDictionary *dic in dicArray) {

         CZHero *hero = [CZHero heroWithDic:dic];

         [tmpArray addObject:hero];

     }

return tmpArray;

}

@end

 

2、在controller中添加属性,并懒加载数据

- (NSArray *)heros

{

    if (_heros == nil) {

        _heros = [CZHero heroList];

    }

    return _heros;

}

3、拖拽一个tableView(使用tableView,必须设置数据源获取数据)代码如下:

- (void)viewDidLoad {

    [super viewDidLoad];

////测试数据

//    NSLog(@"%@",self.heros);

    CZHero *hero = self.heros[0];

    NSLog(@"%@",hero.intro);

    self.tableView.dataSource = self;

4、让controller遵守 数据源的协议UITableViewDataSource代码如下:

#import "ViewController.h"

#import "CZHero.h"

@interface ViewController ()<UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong,nonatomic) NSArray *heros;

@end

5、连线的方式设置数据源

6、添加数据源的方法 

#pragma mark - 实现协议方法

//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

//{

//    return self.heros.count;

//}

////- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

////{

////    self.heros[section]

//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return self.heros.count;

}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

//    创建一个cell并且设置cell的风格

    UITableViewCell *cell  = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];

    CZHero *hero = self.heros[indexPath.row];

    cell.textLabel.text = hero.name;

    cell.imageView.image = [UIImage imageNamed: hero.icon];

    cell.detailTextLabel.text = hero.intro;

//    设置附属物风格

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;

}

效果如下: