MVC简介

   
     MVC是Model-View-Controler的简称
浅谈MVVM框架

       

      Model——即模型。模型一般都有很好的可复用性,统一管理一些我们需要使用的数据。

      View——就是存放视图使用的。

      Controller——控制器它负责处理View和Model的事件。


MVVM简介

     
       MVC框架一目了然,也非常好理解,随着App应用功能的强大Controller的负担越来越大因此在MVC的基础上繁衍出了MVVM框架。
浅谈MVVM框架
      ViewModel: 相比较于MVC新引入的视图模型。是视图显示逻辑、验证逻辑、网络请求等代码存放的地方。

        现实开发中是找到一个合适的框架时使用,并不局限于哪一种,下面举一个简单的例子,在ViewModel里面处理业务逻辑,旨在讲解MVVM框架,不用与工作,当我们处理复杂的业务逻辑的时候可以优先选择MVVM框架。

浅谈MVVM框架

看图简单的逻辑,下面上代码:

User.h和User.m文件

#import <Foundation/Foundation.h>

@interface User : NSObject

@property (nonatomic,copy) NSString *userName;

@property (nonatomic,assign) NSInteger userId;

@end


#import "User.h"

@implementation User

- (id)init{

   self = [superinit];

   if (self) {

       self.userName  =@"";

       self.userId = 20;

    }

    returnself;

}

@end


UserViewModel.h和UserViewModel.m 文件

#import <Foundation/Foundation.h>

@class User;

@interface UserViewModel : NSObject

@property (nonatomic,strong) User *user;

@property (nonatomic,strong) NSString *userName;

@end


#import "UserViewModel.h"

#import "User.h"

@implementation UserViewModel

- (id)init{

   self = [superinit];

   if (self) {

        //在这里处理业务逻辑

        _user = [[Useralloc]init];

        

       if (_user.userName.length > 0) {

            _userName =_user.userName;

        }else {

            _userName = [NSStringstringWithFormat:@"简书%ld", (long)_user.userId];

        }

    }

    returnself;

}


@end


ViewController.m文件


#import "ViewController.h"

#import "UserViewModel.h"

@interface ViewController ()

@property (nonatomic,strong) UILabel *userLabel;

@property (nonatomic,strong) UserViewModel *userViewModel;

@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

 

    _userLabel = [[UILabelalloc]initWithFrame:CGRectMake(10, 199, 200, 50)];

    _userLabel.backgroundColor = [UIColorredColor];

    _userViewModel = [[UserViewModelalloc]init];

    _userLabel.text =_userViewModel.userName;//显示

    [self.viewaddSubview:_userLabel];

    

    // Do any additional setup after loading the view, typically from a nib.

}



这就是简单的MVVM框架使用,工作中要灵活应用,并不局限于哪一种。简单的例子有助于我们理解MVVM框架

相关文章:

  • 2021-08-04
  • 2021-08-26
  • 2022-01-03
  • 2021-06-21
  • 2021-11-07
猜你喜欢
  • 2021-04-11
  • 2021-12-19
  • 2022-12-23
  • 2021-06-20
  • 2021-09-18
  • 2021-09-01
  • 2022-01-03
相关资源
相似解决方案