MVC简介
MVC是Model-View-Controler的简称
Model——即模型。模型一般都有很好的可复用性,统一管理一些我们需要使用的数据。
View——就是存放视图使用的。
Controller——控制器它负责处理View和Model的事件。
MVVM简介
MVC框架一目了然,也非常好理解,随着App应用功能的强大Controller的负担越来越大因此在MVC的基础上繁衍出了MVVM框架。
ViewModel: 相比较于MVC新引入的视图模型。是视图显示逻辑、验证逻辑、网络请求等代码存放的地方。
现实开发中是找到一个合适的框架时使用,并不局限于哪一种,下面举一个简单的例子,在ViewModel里面处理业务逻辑,旨在讲解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框架
|