• iOS MVC、MVP和MVVM理解


    何为架构?
    架构指的是开发中的设计方案。类与类之间的关系,模块与模块之间的关系,客户端与服务器的关系等等都可称之为架构的一部分。
    我们在iOS开发过程中经常听到的架构有:
    MVC、MVP、MVVP、VIPER、CDD
    也有另外一种架构的说法:
    三层架构、四层架构

    一、MVC的理解
    苹果官方给出的关于MVC的理解是:Model-View-Controller

     
    MVC是模型、视图、控制开发模式,对于iOS SDK,所有的View都是视图层,它应该独立于模型层,由视图控制层来控制。所有的用户数据都是模型层,它应该独立于视图。所有的ViewController都是控制层,由它负责控制视图,访问模型数据。
    MVC通讯规则:
    1、Controller ->Model:单向通信,Controller需要将Model呈现给用户,因此需要知道模型的一切,还需要有同Model完全通信的能力,并且能任意使用Model的API。
    2、Controller ->View:单向通信,Ccontroller通过View来布局用户界面。
    3、Model ->View:永远不要直接通信,Model是独立于UI的,并不需要和View直接通信,View通过Controller获取Model数据。
    看如下代码:
    创建一个名为News的模型
    News.h
    #import <Foundation/Foundation.h>
    
    @interface News : NSObject
    @property (copy, nonatomic) NSString *title;
    @property (copy, nonatomic) NSString *content;
    @end
    

    News.m

    #import "News.h"
    
    @implementation News
    
    @end
    

     NewsViewController.h

    #import <UIKit/UIKit.h>
    
    @interface NewsViewController : UITableViewController
    
    @end
    

     NewsViewController.m

    #import "NewsViewController.h"
    #import "News.h"
    
    @interface NewsViewController ()
    @property (strong, nonatomic) NSMutableArray *newsData;
    @property (strong, nonatomic) NSMutableArray *shopData;
    @end
    
    @implementation NewsViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        [self loadNewsData];
    }
    
    //模拟加载model数据,在实际开发中应该是通过网络加载或者获取缓存中的模型数据
    - (void)loadNewsData
    {
        self.newsData = [NSMutableArray array];
        
        for (int i = 0; i < 20; i++) {
            News *news = [[News alloc] init];
            news.title = [NSString stringWithFormat:@"news-title-%d", i];
            news.content = [NSString stringWithFormat:@"news-content-%d", i];
            [self.newsData addObject:news];
        }
    }
    
    #pragma mark - Table view data source
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        return self.newsData.count;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsCell" forIndexPath:indexPath];
        
        News *news = self.newsData[indexPath.row];
        cell.detailTextLabel.text = news.price;
        cell.textLabel.text = shop.name;
        return cell;
    }
    
    @end

    通过上述代码和运行结果可以看到,Model是News,Controller是NewViewController ,View是tableView(包含在Controller中,这是一个tableViewController)。
    现在MVC三元素已经有了,细看一下它的具体实现。
    1、controller确实是拥有了News这个model,并在controller中创建加载这个模型的数据。
    2、controller也拥有了view,这个view就是内置的tableView。
    3、view中并没有拥有News这个model,这两者并没有直接通讯,两者并不知道彼此的存在。
    4、view之所以显示模型数据,是因为Controller把model里面的每一个属性都拿出来赋值到view中的。

    MVC模型的优点:
    1、因为Model和View没有直接联系,互相不知道对方的存在,所以低耦合性,有利于开发分工,有利于组件重用,可维护性高。
    缺点:
    1、Controller的代码过于臃肿,因为它需要连接Model和View的通讯。

    二、MVC的变种
    看如下代码:
    创建一个名为APP的model
    App.h

    #import <Foundation/Foundation.h>
    @interface App : NSObject
    @property (copy, nonatomic) NSString *name;
    @property (copy, nonatomic) NSString *image;
    @end
    

    App.m

    #import "App.h"
    
    @implementation App
    
    @end
    

    创建一个APPView.h

    #import <UIKit/UIKit.h>
    @class App, AppView;
    
    @protocol AppViewDelegate <NSObject>
    @optional
    - (void)appViewDidClick:(AppView *)appView;
    @end
    
    @interface AppView : UIView
    @property (strong, nonatomic) App *app;
    @property (weak, nonatomic) id<AppViewDelegate> delegate;
    @end
    

    APPView.m

    #import "AppView.h"
    #import "App.h"
    
    @interface AppView()
    @property (weak, nonatomic) UIImageView *iconView;
    @property (weak, nonatomic) UILabel *nameLabel;
    @end
    
    @implementation AppView
    
    - (instancetype)initWithFrame:(CGRect)frame
    {
        if (self = [super initWithFrame:frame]) {
            UIImageView *iconView = [[UIImageView alloc] init];
            iconView.frame = CGRectMake(0, 0, 100, 100);
            [self addSubview:iconView];
            _iconView = iconView;
            
            UILabel *nameLabel = [[UILabel alloc] init];
            nameLabel.frame = CGRectMake(0, 100, 100, 30);
            nameLabel.textAlignment = NSTextAlignmentCenter;
            [self addSubview:nameLabel];
            _nameLabel = nameLabel;
        }
        return self;
    }
    
    - (void)setApp:(App *)app
    {
        _app = app;
        self.iconView.image = [UIImage imageNamed:app.image];
        self.nameLabel.text = app.name;
    }
    
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        if ([self.delegate respondsToSelector:@selector(appViewDidClick:)]) {
            [self.delegate appViewDidClick:self];
        }
    }
    
    @end
    

    ViewController.m

    #import "ViewController.h"
    #import "App.h"
    #import "AppView.h"
    
    @interface ViewController () <AppViewDelegate>
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        // 创建view
        AppView *appView = [[AppView alloc] init];
        appView.frame = CGRectMake(100, 100, 100, 150);
        appView.delegate = self;
        [self.view addSubview:appView];
        
        // 加载模型数据
        App *app = [[App alloc] init];
        app.name = @"QQ";
        app.image = @"QQ";
        
        // 设置数据到view上
        appView.app = app;
    }
    
    #pragma mark - AppViewDelegate
    - (void)appViewDidClick:(AppView *)appView
    {
        NSLog(@"控制器监听到了appView的点击");
    }
    
    @end

    通过上述代码可以看出:
    1、model作为一个对象被添加到view中,model中的数据在创建model的时候被使用。
    2、view中的控件被隐藏,外界不知道view内部的结构。
    3、对controller进行了瘦身,在controller中只需要传入model对象给view即可。
    优点:对Controller进行瘦身,将view内部的细节封装起来,外界不知道view内部的具体实现。
    缺点:view依赖于model。

    三、MVP
    Model-View-Presenter(主持者):跟MVC模型类似,只不过是用Presenter代替了Controller来对model和view进行调度。
    看如下代码:
    APP和APPView代码跟上面代码一致,我们此时需要增加一个AppPresenter文件
    AppPresenter.h

    #import <UIKit/UIKit.h>
    
    @interface AppPresenter : NSObject
    - (instancetype)initWithController:(UIViewController *)controller;
    @end
    

    AppPresenter.m

    #import "AppPresenter.h"
    #import "App.h"
    #import "AppView.h"
    
    @interface AppPresenter() <AppViewDelegate>
    @property (weak, nonatomic) UIViewController *controller;
    @end
    
    @implementation AppPresenter
    
    - (instancetype)initWithController:(UIViewController *)controller
    {
        if (self = [super init]) {
            self.controller = controller;
             // 创建View
            AppView *appView = [[AppView alloc] init];
            appView.frame = CGRectMake(100, 100, 100, 150);
            appView.delegate = self;
            [controller.view addSubview:appView];
            // 加载模型数据
            App *app = [[App alloc] init];
            app.name = @"QQ";
            app.image = @"QQ";
            // 赋值数据
            [appView setName:app.name andImage:app.image];
        }
        return self;
    }
    
    #pragma mark - AppViewDelegate
    - (void)appViewDidClick:(AppView *)appView
    {
        NSLog(@"presenter 监听了 appView 的点击");
    }
    @end
    

    ViewController.m

    #import "ViewController.h"
    #import "AppPresenter.h"
    
    @interface ViewController ()
    @property (strong, nonatomic) AppPresenter *presenter;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.presenter = [[AppPresenter alloc] initWithController:self];
    }
    
    @end
    

    通过上述代码可以看出:
    1.通过一个Presenter的中间媒介把原来在controller中的逻辑放在自己的实现方法里。
    2.如果controller中需要不同的模块,可以创建多个Presenter来实现。比如想在controller中增加两个view,可以创建两个Presenter实现这两个view的实现。

    四、MVVM
    概念:MVVM是model-view-viewModel的缩写,它是一种基于前端开发的架构模式,核心是提供对view和ViewModel的双向数据绑定,这使得ViewModel的状态改变可以自动传递给View,即所谓的数据双向绑定。在H5还未流行的时候MVC作为web的最佳实践是OK的,因为Web应用的View相对来说比较简单,前端所需的数据在后端基本上都可以处理好,View层主要是做展示,用Controller来处理复杂的业务逻辑。所以View层相对来说比较轻量,就是所谓的瘦客户端思想。
    看如下代码:
    News.h

    #import <Foundation/Foundation.h>
    
    @interface News : NSObject
    @property (copy, nonatomic) NSString *title;
    @property (copy, nonatomic) NSString *content;
    @end
    

    News.m

    @implementation News
    
    @end
    

    NewsViewModel.h

    #import <Foundation/Foundation.h>
    
    
    @interface NewsViewModel : NSObject
    
    -(void)loadNewsData:(void (^)(NSArray *newsDdata))completion;
    
    @end
    

    NewsViewModel.m

    #import "NewsViewModel.h"
    #import "News.h"
    @implementation NewsViewModel
    
    //通常在此处发送网络请求获取数据,实现数据转字典模型等操作
    -(void)loadNewsData:(void (^)(NSArray *))completion
    {
        if (!completion) return;
        
        NSMutableArray *newsData = [NSMutableArray array];
           
           for (int i = 0; i < 20; i++) {
               News *news = [[News alloc] init];
               news.title = [NSString stringWithFormat:@"news-title-%d", i];
               news.content = [NSString stringWithFormat:@"news-content-%d", i];
               [newsData addObject:news];
           }
        completion(newsData);
    }
    @end
    

    NewsViewController.m

    #import "NewsViewController.h"
    #import "News.h"
    #import "NewsViewModel.h"
    @interface NewsViewController ()
    @property (strong, nonatomic) NSMutableArray *newsData;
    @property (strong, nonatomic) NewsViewModel *newsVM;
    
    @end
    
    @implementation NewsViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.newsVM = [[NewsViewModel alloc] init];
        [self.newsVM loadNewsData:^(NSArray *newsDdata) {
            self.newsData = newsDdata;
        }];
    }
    
    
    #pragma mark - Table view data source
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        return self.newsData.count;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsCell" forIndexPath:indexPath];
        MJNews *news = self.newsData[indexPath.row];
        cell.detailTextLabel.text = news.content;
        cell.textLabel.text = news.title;
        return cell;
    }
    

    通过上诉代码可以知道:
    1、viewModel中发送网络请求、实现字典转模型操作。
    2、在Controller中获取viewModel的值,然后将数据传递给view显示。

    五、MVVM变种
    基于上面MVC变种,我们可以仿照它实现MVVM的变种。
    看如下代码:
    App.h

    import <Foundation/Foundation.h>
    
    @interface App : NSObject
    @property (copy, nonatomic) NSString *name;
    @property (copy, nonatomic) NSString *image;
    @end
    

    App.m

    #import "App.h"
    
    @implementation App
    
    @end
    

    AppView.h

    #import <UIKit/UIKit.h>
    
    @class AppView, AppViewModel;
    
    @protocol AppViewDelegate <NSObject>
    @optional
    - (void)appViewDidClick:(AppView *)appView;
    @end
    
    @interface AppView : UIView
    @property (weak, nonatomic) AppViewModel *viewModel;
    @property (weak, nonatomic) id<AppViewDelegate> delegate;
    @end
    

    AppView.m

    #import "AppView.h"
    #import "NSObject+FBKVOController.h"
    
    @interface AppView()
    @property (weak, nonatomic) UIImageView *iconView;
    @property (weak, nonatomic) UILabel *nameLabel;
    @end
    
    @implementation AppView
    
    - (instancetype)initWithFrame:(CGRect)frame
    {
        if (self = [super initWithFrame:frame]) {
            UIImageView *iconView = [[UIImageView alloc] init];
            iconView.frame = CGRectMake(0, 0, 100, 100);
            [self addSubview:iconView];
            _iconView = iconView;
            
            UILabel *nameLabel = [[UILabel alloc] init];
            nameLabel.frame = CGRectMake(0, 100, 100, 30);
            nameLabel.textAlignment = NSTextAlignmentCenter;
            [self addSubview:nameLabel];
            _nameLabel = nameLabel;
        }
        return self;
    }
    
    - (void)setViewModel:(AppViewModel *)viewModel
    {
        _viewModel = viewModel;
        
        __weak typeof(self) waekSelf = self;
        [self.KVOController observe:viewModel keyPath:@"name" options:NSKeyValueObservingOptionNew block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSKeyValueChangeKey,id> * _Nonnull change) {
            waekSelf.nameLabel.text = change[NSKeyValueChangeNewKey];
        }];
        
        [self.KVOController observe:viewModel keyPath:@"image" options:NSKeyValueObservingOptionNew block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSKeyValueChangeKey,id> * _Nonnull change) {
            waekSelf.iconView.image = [UIImage imageNamed:change[NSKeyValueChangeNewKey]];
        }];
    }
    
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        if ([self.delegate respondsToSelector:@selector(appViewDidClick:)]) {
            [self.delegate appViewDidClick:self];
        }
    }
    
    @end
    

    AppViewModel.h

    #import <UIKit/UIKit.h>
    
    @interface AppViewModel : NSObject
    - (instancetype)initWithController:(UIViewController *)controller;
    @end
    

    AppViewModel.m

    #import "AppViewModel.h"
    #import "App.h"
    #import "AppView.h"
    
    @interface AppViewModel() <AppViewDelegate>
    @property (weak, nonatomic) UIViewController *controller;
    @property (copy, nonatomic) NSString *name;
    @property (copy, nonatomic) NSString *image;
    @end
    
    @implementation AppViewModel
    
    - (instancetype)initWithController:(UIViewController *)controller
    {
        if (self = [super init]) {
            self.controller = controller;
            
            // 创建View
            AppView *appView = [[AppView alloc] init];
            appView.frame = CGRectMake(100, 100, 100, 150);
            appView.delegate = self;
            appView.viewModel = self;
            [controller.view addSubview:appView];
            
            // 加载模型数据
            App *app = [[App alloc] init];
            app.name = @"QQ";
            app.image = @"QQ";
            
            // 设置数据
            self.name = app.name;
            self.image = app.image;
        }
        return self;
    }
    
    #pragma mark - AppViewDelegate
    - (void)appViewDidClick:(AppView *)appView
    {
        NSLog(@"viewModel 监听了 appView 的点击");
    }
    
    @end
    

    ViewController.m

    #import "ViewController.h"
    #import "AppViewModel.h"
    
    @interface ViewController ()
    @property (strong, nonatomic) AppViewModel *viewModel;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        self.viewModel = [[AppViewModel alloc] initWithController:self];
    }
    
    @end
    

    通过上述代码可以得知:
    1、把view放到viewModel中而不是controller中。这样让controller持有viewModel即可。
    2、在viewmodel中对数据进行处理,如发送网络请求、字典转模型。把得到的数据传递到view中。

    六、MVC和MVVM的区别
    最大的区别是:实现了View和Model的自动更新,也就是说当model的属性发生改变时,我们不再手动的操作,通过viewModel来处理数据的业务逻辑,这种低耦合模式提高代码的可重用性。
    总的来说MVVM比MVC精简很多,一定程度上简化了界面与业务的依赖性,也解决了数据的频繁更新问题。对于这两种模式,可能比较复杂的情况下分不清Model和View,但是在实际开发中大可不必纠结。只要掌握了架构的思想,针对不同的业务情况,选择最适合的架构来解决问题即可。

    七、三层架构和四层架构

    界面层:一般指的是跟界面显示有关的层面。
    业务层:就是一些点击事件。
    数据层:负责数据库或者网络请求获取的数据。
    比如实现一个新闻列表的功能。新闻列表界面(即tableView)就是界面层,加载新闻数这一功能就是业务层,而数据的来源则是数据层。

    与三层架构不同的是多了一个网络层,这样更加精细的分工可以把网络请求和数据层实现分离。

     
    来源:简书
  • 相关阅读:
    首次调用u8api遇到的问题总结
    为datagridview添加自定义按钮
    我对数据库索引的初步了解
    ObjectARX 常见编译错误解决方式记录
    手动修改Visual Studio 版本互转工具
    [经验] FAS 20号指令的深入研究
    Object ARX 统一设置所有图层的RGB颜色
    ARX 选择集获得所有图形 遍历 实例 备忘
    ObjectARX2010 学习笔记002:读取已经存在的DWG文件中的内容
    利用编译时的全局声明对抗反编译
  • 原文地址:https://www.cnblogs.com/GJ-ios/p/13139565.html
Copyright © 2020-2023  润新知