zoukankan      html  css  js  c++  java
  • iOS 架构模式MVVM


    MVVM

    Model-View-ViewModel
    MVVM 其实是MVC的进化版,他将业务逻辑从VC中解耦到ViewModel,实现VC的瘦身。

    做一个简单的登录判断:

    创建LoginViewModel(逻辑处理),LoginModel(只放数据),LoginViewController。 这里不用LoginView是为了能更好的把精力集中在用ViewModel解耦上。

    在LoginModel中加入方法

    //.h
    - (instancetype)initWithUserName:(NSString *)username password:(NSString *)password;
    
    @property (nonatomic,copy,readonly)NSString * username;
    @property (nonatomic,copy,readonly)NSString * password;
    
    //.m
    - (instancetype)initWithUserName:(NSString *)username password:(NSString *)password {
        if (self = [super init]) {
            _username = username;
            _password = password;
        }
        return self;
    }
    

    在LoginViewModel中加入方法

    //.h
    import "PersonModel.h" - (instancetype)initWithPerson:(PersonModel *)person; @property (nonatomic,assign,readonly)BOOL canLogin;


    //.m
    - (instancetype)initWithPerson:(PersonModel *)person {
        if (self = [super init]) {
         //在这做你绑定model后的处理
          _canLogin = [self valiCanLoginWithUserName:person.username password:person.password];
        }
        return self;
    }
    
    - (BOOL)valiCanLoginWithUserName:(NSString *)username password:(NSString *)password {
        if (username.length & password.length) {
            return YES;
        } else {
            return NO;
        }
    }
    

    然后VC(或者View)就可以直接这样获得判断后的结果

    PersonModel * person = [[PersonModel alloc]initWithUserName:@"10" password:@"10"];
    PersonViewModel * viewModel = [[PersonViewModel alloc]initWithPerson:person];
    NSLog(@"%d",viewModel.canLogin);
    

    简单的功能的时候没什么,当你处理复杂的逻辑判断的时候,MVVM会有巨大优势。

  • 相关阅读:
    全文索引的书
    图片上传预览
    sqlserver 递归删除组织结构树
    dataset 转泛型list
    jquery easyui tree 异步加载数据
    sqlserver 禁用外键
    linx 实用操作命令二
    Compilation failed: this version of PCRE is not compiled with PCRE_UTF8 support at offset 0
    Centos linux php扩展安装步骤
    linux Apache和php配置
  • 原文地址:https://www.cnblogs.com/hlgbys/p/5497201.html
Copyright © 2011-2022 走看看