iOS MVVM之从理论到实践

iOS UI设计模式

MVC 模式

MVC 概念

image

  • Modal 模型对象:模型对象封装了应用程序的数据,并定义操控和处理该数据的逻辑和运算。模型(Model)实际上考虑的是“什么”的问题,即你的程序是什么?以纸牌匹配游戏为例子,模型就是设计这个游戏怎么玩,花色匹配,数值匹配得多少分,等逻辑问题。以及这个游戏里的类,如:纸牌,牌堆等类都属于模型里面的东西。以上都是独立于UI且在模型中的。

  • Controller 控制器对象:控制器(Controller)控制模型如何呈现在屏幕上,即弄清如何将这些牌显示在屏幕上,然后将其用动画的形式表现。

  • View 视图对象:视图对象是应用程序中用户可以看见的对象。视图(View)是控制器的侍从,是控制器要使用的类,用于构建UI。

MVC 各层之间的通信

  • Controller要完全知道Model的内容,不受限制地访问Model;相反,Model 通过 Notification 和 KVO 机制与 Controller 间接通信。

  • Controller也能与View通信,如通过outlet;相反View也能与Controller通信,但是View是通用的,所以它不能对Controller的类知道得太多,只能以一种“盲”的方式去通信,如关联一个action、委托(delegate)协议。

  • Model 和 View 永远不能相互通信,只能通过 Controller 传递。

MVVM 模式

MVVM 概念

image

这个模式的核心是ViewModel,它是一种特殊的model类型,用于表示程序的UI状态。它包含描述每个UI控件的状态的属性。例如,文本输入域的当前文本,或者一个特定按钮是否可用。它同样暴露了视图可以执行哪些行为,如按钮点击或手势。可以将ViewModel看作是视图的模型(model-of-the-view)。MVVM模式中的三部分比MVC更加简洁,下面是一些严格的限制:
- View引用了ViewModel,但反过来不行。

  • ViewModel引用了Model,但反过来不行。
    如果我们破坏了这些规则,便无法正确地使用MVVM。

View引用了ViewModel,但ViewModel没有引用View,那ViewModel如何更新视图呢?MVVM模式依赖于数据绑定,它是一个框架级别的特性,用于自动连接对象属性和UI控件。

MVVM项目实践

效果展示

  • 登录:一个普通的登录功能,输入账号密码登录程序
  • 主页:展示好友,支持刷新及加载更多,并提供一个搜索和退出的功能。
  • 搜索结果页:展示搜索的好友。

image

image

image

项目构建

  1. 创建项目MVVMExample,添加Model、View、ViewModel等文件夹,项目结构如下:

image

  1. 使用CocoaPods添加一些需要使用的库。
    pod 'ReactiveObjC'
    pod 'Masonry', '~>1.1.0'
    pod 'AFNetworking', '~> 3.1.0'
    pod 'MBProgressHUD', '~> 1.1.0'
    pod 'SDWebImage', '~> 4.3.2'
    pod 'LinqToObjectiveC', '~> 2.1.0'
    pod 'FMDB', '~> 2.7.2'
    pod 'MJRefresh', '~> 3.1.15.3'

实现登录功能

登录的准备工作

  1. 搭建登录界面,登录界面非常简洁只有一个账号输入框、一个密码输入框和一个登录按钮。创建一个LoginViewController,并在viewDidLoad方法中加入如下代码。
    //创建界面元素
    UITextField *userNameTextField = [[UITextField alloc] init];
    userNameTextField.borderStyle = UITextBorderStyleRoundedRect;
    userNameTextField.placeholder = @"请输入用户名…";
    [userNameTextField becomeFirstResponder];
    [self.view addSubview:userNameTextField];
    self.userNameT = userNameTextField;

    UITextField *passwordTextField = [[UITextField alloc] init];
    passwordTextField.borderStyle = UITextBorderStyleRoundedRect;
    passwordTextField.placeholder = @"请输入密码…";
    passwordTextField.secureTextEntry =  YES;
    [self.view addSubview:passwordTextField];
    self.passWordT = passwordTextField;

    UIButton *loginButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [self.view addSubview:loginButton];
    self.loginB = loginButton;

    //布局界面元素
    [passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(10);
        make.centerY.equalTo(self.view.mas_centerY);
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.height.equalTo(@30);
    }];
    [userNameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(10);
        make.bottom.equalTo(passwordTextField.mas_top).offset(-10);
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.height.equalTo(@(30));
    }];
    [loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(passwordTextField.mas_left).offset(44);
        make.top.equalTo(passwordTextField.mas_bottom).offset(10);
        make.right.equalTo(passwordTextField.mas_right).offset(-44);
        make.height.equalTo(@(30));
    }];
  1. 创建用户数据模型类UserModel,我习惯于把数据跟逻辑分开,只有简单的几个属性,便于后面的传递与使用。
#import <Foundation/Foundation.h>


@interface UserModel : NSObject


@property (copy, nonatomic) NSString *username;
@property (copy, nonatomic) NSString *password;
@property (assign, nonatomic, getter=isLogined) BOOL logined;


+ (instancetype)userModelWithUsername:(NSString *)username password:(NSString *)password logined:(BOOL)logined;
- (instancetype)initWithUsername:(NSString *)username password:(NSString *)password logined:(BOOL)logined;


@end
  1. 创建业务功能类Services:这个功能类实现了项目的主要功能,登录、登出、获取好友、查找好友等。
@interface Result : NSObject


@property (assign, nonatomic) BOOL success;
@property (copy, nonatomic) NSString *message;
@property (strong, nonatomic) id responseObject;


+ (instancetype)resultWithSuccess:(BOOL)success message:(NSString *)message responseObject:(id)responseObject;
- (instancetype)initWithSuccess:(BOOL)success message:(NSString *)message responseObject:(id)responseObject;


@end


@interface Services : NSObject


- (RACSignal *)loginSignal:(NSString *)userName passWord:(NSString *)passWord;
- (RACSignal *)logoutSignal:(NSString *)userName passWord:(NSString *)passWord;


- (RACSignal *)searchSignal:(NSString *)searchText;
- (RACSignal *)allFriendsSignal;
- (RACSignal *)friendSignalWithPage:(NSInteger)page andCount:(NSInteger)count;
- (RACSignal *)searchSignalWithContent:(NSString *)content page:(NSInteger)page andCount:(NSInteger)count;


@end
  1. 接着创建业务逻辑模型类User:包涵用户的基本数据和行为逻辑。
@interface User : NSObject


@property (strong, nonatomic, readonly) Services *services;
@property (strong, nonatomic) UserModel *userModel;
@property (assign, nonatomic, readonly, getter=isValidOfUsername) BOOL validOfUsername;
@property (assign, nonatomic, readonly, getter=isValidOfPassword) BOOL validOfPassword;


+ (instancetype)userWithServices:(Services *)services userModel:(UserModel *)model;
- (instancetype)initWithServices:(Services *)services userModel:(UserModel *)model;


- (RACSignal *)loginSignal;
- (RACSignal *)logoutSignal;


@end

ViewModel与数据绑定

  1. 创建第一个ViewModel:LoginViewModel,添加如下方法与属性:
@property (strong, nonatomic) User *user;
@property (strong, nonatomic) RACCommand *loginCommand;


+ (instancetype)loginViewModelWithUser:(User *)user;
- (instancetype)initWithUser:(User *)user;

前面说了ViewModel,它是一种特殊的model类型,用于表示程序的UI状态。它包含描述每个UI控件的状态的属性。但是我还是把用户名和密码放到数据层,方便传递,因为ViewModel拥有Model,所以并不影响他表示的UI状态、包含描述每个UI控件的状态的属性。

  1. 补充RACCommand,上一篇文章iOS MVVM之ReactiveCocoa并未提及。

RACCommand 并不表示数据流,它只是一个继承自 NSObject 的类,但是它却可以用来创建和订阅用于响应某些事件的信号。它本身并不是一个 RACStream 或者 RACSignal 的子类,而是一个用于管理 RACSignal 的创建与订阅的类。RACCommand的基本属性:
- executionSignals:需要执行的block成功的时候返回的信号,他是在主线程执行的。
- executing:判断当前的block是否在执行,执行完之后会返回@(NO).
- enabled:当前命令是否enabled,默认是no,他也可以根据enableSignal来设置或者allowsConcurrentExecution设置为NO的时候(command已经开始执行)
- errors:执行command的时候获取的error都会通过这个信号发送
- allowsConcurrentExecution:是否允许并发执行command,默认是NO。
- initWithSignalBlock:(RACSignal * (^)(id input))signalBlock:初始化RACCommand,参数为返回一个信号的block,即block返回的是executionSignals
- initWithEnabled:(RACSignal )enabledSignal signalBlock:(RACSignal (^)(id input))signalBlock:第一个参数设置当前command是否可用,第二个是执行的block。enableed默认是yes,所以第二个参数也可以为nil。
- execute:(id)input:调用command,input为executionSignals的订阅者发送的值

  1. 实现LoginViewModel

非常简洁的一个ViewModel,只实现了其工厂方法,初始化user属性以及loginCommand。

+ (instancetype)loginViewModelWithUser:(User *)user {
    return [[self alloc] initWithUser:user];
}
- (instancetype)initWithUser:(User *)user {
    if (self = [super init]) {
        self.user = user;

        //创建有效的用户名密码信号
        @weakify(self);
        RACSignal *validUS = [[RACObserve(self.user.userModel, username) map:^id _Nullable(id  _Nullable value) {
            @strongify(self);
            return @(self.user.isValidOfUsername);
        }] distinctUntilChanged];
        RACSignal *validPS = [[RACObserve(self.user.userModel, password) map:^id _Nullable(id  _Nullable value) {
            @strongify(self);
            return @(self.user.isValidOfPassword);
        }] distinctUntilChanged];

        //合并有效的用户名密码信号作为控制登录按钮可用的信号
        RACSignal *validLS = [RACSignal combineLatest:@[validUS, validPS] reduce:^id _Nonnull(id first, id second) {
            return @([first boolValue] && [second boolValue]);
        }];

        self.loginCommand = [[RACCommand alloc] initWithEnabled:validLS signalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            @strongify(self);
            return [[self.user loginSignal] logAll];
        }];
    }

    return self;
}
  1. 数据绑定
    在LoginViewController.m文件中添加如下方法:
- (void)bindViewModel {
    self.userNameT.text = self.viewModel.user.userModel.username;
    self.passWordT.text = self.viewModel.user.userModel.password;
    RAC(self.viewModel.user.userModel, username) = self.userNameT.rac_textSignal;
    RAC(self.viewModel.user.userModel, password) = self.passWordT.rac_textSignal;
    self.loginB.rac_command = self.viewModel.loginCommand;
    @weakify(self)
    [self.viewModel.loginCommand.executing subscribeNext:^(NSNumber * _Nullable x) {
        @strongify(self)
        BOOL end = [x boolValue];
        [UIApplication sharedApplication].networkActivityIndicatorVisible = end;
        if (end) {
            [LoadingTool showTo:self.view];
        } else {
            [LoadingTool hideFrom:self.view];
        }
    }];
    [self.viewModel.loginCommand.executionSignals subscribeNext:^(RACSignal *signal) {
        @strongify(self)
        [signal subscribeNext:^(ResultModel *model) {
            [self.userNameT resignFirstResponder];
            [self.passWordT resignFirstResponder];

            if (model.success) {
                HomeViewController *homeCtr = [HomeViewController homeViewControllerWithViewModel:[[HomeViewModel alloc] initWithHome:[Home homeWithUser:model.dataModel]]];
                [UIApplication sharedApplication].delegate.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:homeCtr];
                [[UIApplication sharedApplication].delegate.window makeKeyWindow];
            } else {
                [LoadingTool showMessage:model.message toView:self.view];
            }
        }];
    }];
}

这个方法主要是做了这两件事情,一个是呈现初始化数据;另一个是对控件和数据进行绑定,极大的简化UI与数据的交互,绑定后的能够及时的对数据进行跟新并且能够适时的通知控件。

  1. 小结
    • Model层暴露服务并负责提供程序的业务逻辑实现。
    • ViewModel层表示程序的视图状态(view-state)。同时响应用户交互及来自Model层的事件,两者都受view-state变化的影响。
    • View层很薄,只提供ViewModel状态的显示及输出用户交互事件。

实现列表展示页(首页好友)

列表展示模型层处理

  1. 在Model分组中,添加一个FriendModel类,并添加3个属性以及工厂方法、初始化方法。
@interface FriendModel : NSObject


@property (copy, nonatomic) NSString *uin;
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *img;


+ (instancetype)friendModelWithInfo:(NSDictionary *)info;
- (instancetype)initWithInfo:(NSDictionary *)info;


@end

这个模型表示,首页好友接口返回的一个好友的数据对象。

  1. 添加一个Home模型类,这个类应包涵首页的业务逻辑。
@property (strong, nonatomic, readonly) User *user;


+ (instancetype)homeWithUser:(User *)user;
- (instancetype)initWithUser:(User *)user;


- (RACSignal *)friendSignalWithPage:(NSInteger)page andCount:(NSInteger)count;


@end

列表展示ViewModel层处理

  1. 在ViewModel分组中添加FriendCellViewModel,提供如下方法与属性:
@interface FriendCellViewModel : NSObject


@property (strong, nonatomic) FriendModel *friendModel;


+ (instancetype)friendCellViewModel:(FriendModel *)model;
- (instancetype)initWithFriendModel:(FriendModel *)model;


@end

从目前来看,这一层毫无用处,仅仅是对model做了一个中转。表面上的确如此,因为这个实力非常简单,对Cell没有复杂的交互和业务。这样的情况是可以整合到一个ViewModel上,可以少写一个Model并不会有任何影响。其实这里面的业务逻辑层已经被减去了。

  1. 添加一个HomeViewModel如下:
@interface HomeViewModel : NSObject


@property (copy, nonatomic) NSString *title;
@property (strong, nonatomic, readonly) Home *home;
@property (copy, nonatomic) NSArray<FriendCellViewModel *> *dataArr;
@property (copy, nonatomic)


- (instancetype)initWithHome:(Home *)home;
- (RACSignal *)pageSignal;


@end

分别是表示表题、逻辑模型、结果列表以及一个获取数据的信号方法。

列表展示数据绑定及页面渲染

  1. 在View层添加FriendTableViewCell、LoginViewController具体就不赘述,与登录类似。

  2. FriendTableViewCell数据绑定,这个也十分简单,这里处理的非常简单,仅仅是对初始化数据进行展示:

- (void)bindViewModel:(FriendCellViewModel *)viewModel {
    self.viewModel = viewModel;

    self.textLabel.text = self.viewModel.friendModel.name;
    self.detailTextLabel.text = self.viewModel.friendModel.uin;
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:self.viewModel.friendModel.img] placeholderImage:[UIImage imageNamed:@"50"]];
}
  1. LoginViewController数据绑定,主要就是标题的呈现与列表的更新。
- (void)bindViewModel {
    self.title = self.viewModel.title;

    @weakify(self)
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [[self.viewModel pageSignal:isDown] subscribeNext:^(ResultModel *model) {
        @strongify(self)
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        if (model.success) {
            if (model.dataModel == nil || [(NSArray *)model.dataModel count] == 0) {
                [LoadingTool showMessage:isDown ? @"没有数据" : @"没有跟多数据" toView:self.view];
            }
        } else {
            [LoadingTool showMessage:model.message toView:self.view];
        }
        if (isDown) {
            [self.tableView.mj_header endRefreshing];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
    }];
    [RACObserve(self.viewModel, dataArr) subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        [self.tableView reloadData];
    }];
}
  1. 渲染列表页,基本上就是实现UITableViewDelegate, UITableViewDataSource这两个代理方法。

为列表页增加下拉刷新上拉加载更多功能

  1. 对HomeViewModel增加页码及页码数属性,并修改数据获取信号方法。
@property (assign, nonatomic, readonly) NSInteger page;
@property (assign, nonatomic, readonly) NSInteger pageCount;


- (RACSignal *)pageSignal:(BOOL)isFirst;
  1. 在LoginViewController中添加如下方法,把对数据获取信号的订阅分离出去。
/**
 加载tableView


 @param isDown 是否为下拉加载
 */
- (void)loadTableView:(BOOL)isDown {
    @weakify(self)
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [[self.viewModel pageSignal:isDown] subscribeNext:^(ResultModel *model) {
        @strongify(self)
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        if (model.success) {
            if (model.dataModel == nil || [(NSArray *)model.dataModel count] == 0) {
                [LoadingTool showMessage:isDown ? @"没有数据" : @"没有跟多数据" toView:self.view];
            }
        } else {
            [LoadingTool showMessage:model.message toView:self.view];
        }
        if (isDown) {
            [self.tableView.mj_header endRefreshing];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
    }];
}
  1. 修改绑定方法,这里使用MJRefresh来做加载,不熟悉可以先了解一下:
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadTableView:YES];
    }];
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadTableView:NO];
    }];
    self.tableView.mj_footer.automaticallyChangeAlpha = YES;

搜索功能及退出功能

从上面实现的功能来看,一切都是套路,就不啰嗦了。有兴趣就下载代码看看。

代码地址

下载代码请点击

猜你喜欢

转载自blog.csdn.net/jiuchabaikaishui/article/details/80423893