iOS MVVM架构简单使用

开篇
MVC Model-View-Controller是一个用来组织代码的权威范式。Apple甚至是这么说的。在MVC下,所有的对象被归类为一个model,一个view,或一个controller。Model持有数据,View显示与用户交互的界面,而View Controller调解Model和View之间的交互。
MVVM MVVM的出现主要是为了解决在开发过程中Controller越来越庞大的问题,变得难以维护,所以MVVM把数据加工的任务从Controller中解放了出来,使得Controller只需要专注于数据调配的工作,ViewModel则去负责数据加工并通过通知机制让View响应ViewModel的改变。

效果图


9a16f55c773f2312664c0818e2d5864b.png

源码分析
1.Model模块

首先是model层的代码,创建MovieModel类,继承自NSObject。设置几个属性movieName、year、imageUrl、detailUrl(用于跳转)

#import <Foundation>

@interface MovieModel : NSObject
@property (strong, nonatomic) NSString *movieName;
@property (strong, nonatomic) NSString *year;
@property (strong, nonatomic) NSURL *imageUrl;
@property (strong, nonatomic) NSString *detailUrl;
@end

ViewController模块

ViewController里面是用来从MovieViewModel中获取数据信息然后展示到UITableView的cell上面,和点击单元格的页面跳转

#import "HomeViewController.h"
#import "MovieViewModel.h"
#import "MovieCell.h"
@interface HomeViewController ()<UITableViewDataSource>

@property (nonatomic,strong) NSArray *modelArray;
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"电影首页";
    self.view.backgroundColor = [UIColor redColor];

    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.rowHeight = 80;
    [self.view addSubview:tableView];
    [tableView registerClass:[MovieCell class] forCellReuseIdentifier:@"MovieCell"];

    //初始化MovieViewModel,设置成功(returnBlock)和失败的回调(errorBlock),getMovieData去请求数据,请求数据成功即回调上一步设置的returnBlock,请求失败则回调errorBlock
    MovieViewModel *viewModel = [[MovieViewModel alloc] init];
    viewModel.returnBlock = ^(id returnValue){

        _modelArray = returnValue;
        [tableView reloadData];
    };
    viewModel.errorBlock = ^(id errorCode){

        NSLog(@"%@",errorCode);
    };

    [viewModel getMovieData];

}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MovieCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MovieCell"];
    cell.model = _modelArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MovieViewModel *movieViewModel = [[MovieViewModel alloc] init];
    [movieViewModel movieDetailWithPublicModel:_modelArray[indexPath.row] WithViewController:self];
}

@end

View模块

view这里跟MVC中子类化UITableViewCell一样,将model数据传进来,复写setModel方法给视图传递数据

#import "MovieModel.h"
@interface MovieCell : UITableViewCell
@property (nonatomic,strong) MovieModel *model;
@end

#import "MovieCell.h"
#import "UIImageView+AFNetworking.h"
@interface MovieCell()
@property (nonatomic,strong) UILabel *nameLabel;
@property (nonatomic,strong) UILabel *yearLabel;
@property (nonatomic,strong) UIImageView *imgView;
@end
@implementation MovieCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _imgView = [[UIImageView alloc] initWithFrame:CGRectMake(15, 10, 40, 60)];
        [self.contentView addSubview:_imgView];

        _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 10, 200, 20)];
        [self.contentView addSubview:_nameLabel];

        _yearLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 50, 100, 20)];
        _yearLabel.textColor = [UIColor lightGrayColor];
        _yearLabel.font = [UIFont systemFontOfSize:14];
        [self.contentView addSubview:_yearLabel];
    }
    return self;
}

- (void)setModel:(MovieModel *)model{
    _model = model;
    _nameLabel.text = _model.movieName;
    _yearLabel.text = _model.year;
    [_imgView setImageWithURL:_model.imageUrl];
}

@end

ViewModel模块

ViewModel是最重要的模块: 1.这里面进行了数据的网络请求,并将数据转换成model放在一个数组中,调用_returnBlock将model数组传递给viewController进行数据源的处理 2.将页面跳转的逻辑放在ViewModel中,点击单元格进行页面跳转的时候直接在- (void)tableView:(UITableView )tableView didSelectRowAtIndexPath:(NSIndexPath )indexPath中调用MovieViewModel的该方法即可

#import <Foundation>
#import "MovieModel.h"
#import <UIKit>

typedef void (^ReturnValueBlock) (id returnValue);
typedef void (^ErrorCodeBlock) (id errorCode);

@interface MovieViewModel : NSObject
@property (nonatomic,copy) ReturnValueBlock returnBlock;
@property (nonatomic,copy) ErrorCodeBlock errorBlock;

//获取电影数据
- (void)getMovieData;
//跳转到电影详情页
- (void)movieDetailWithPublicModel: (MovieModel *)movieModel WithViewController: (UIViewController *)superController;
@end

#import "MovieViewModel.h"
#import "NetworkService.h"
#import "MovieModel.h"
#import "MovieViewController.h"

@implementation MovieViewModel

- (void)getMovieData{
    [NetworkService requestWithURL:@"/v2/movie/coming_soon" params:nil success:^(id result) {
        NSLog(@"%@",result);

        NSArray *subjects = result[@"subjects"];
        NSMutableArray *modelArr = [NSMutableArray arrayWithCapacity:subjects.count];
        for (NSDictionary *subject in subjects) {
            MovieModel *model = [[MovieModel alloc] init];
            model.movieName = subject[@"title"];
            model.year = subject[@"year"];
            NSString *urlStr = subject[@"images"][@"medium"];
            model.imageUrl = [NSURL URLWithString:urlStr];
            model.detailUrl = subject[@"alt"];
            [modelArr addObject:model];
        }
        _returnBlock(modelArr);

    } failure:^(NSError *error) {
         NSLog(@"%@",error);
        _errorBlock(error);
    }];
}

- (void)movieDetailWithPublicModel: (MovieModel *)movieModel WithViewController: (UIViewController *)superController{
    MovieViewController *movieVC = [[MovieViewController alloc] init];
    movieVC.url = movieModel.detailUrl;
    [superController.navigationController pushViewController:movieVC animated:YES];
}
@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容