MVC簡介
MVC是Model-View-Controler的簡稱
Model——即模型。模型一般都有很好的可復用性,統一管理一些我們需要使用的數據。
View——就是存放視圖使用的。
Controller——控制器它負責處理View和Model的事件。
MVVM簡介
MVC框架一目了然,也非常好理解,隨著App應用功能的強大Controller的負擔越來越大因此在MVC的基礎上繁衍出了MVVM框架。
ViewModel: 相比較于MVC新引入的視圖模型。是視圖顯示邏輯、驗證邏輯、網絡請求等代碼存放的地方。
現實開發(fā)中是找到一個合適的框架時使用,并不局限于哪一種,下面舉一個簡單的例子,在ViewModel里面處理業(yè)務邏輯,旨在講解MVVM框架,不用與工作,當我們處理復雜的業(yè)務邏輯的時候可以優(yōu)先選擇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) {
//在這里處理業(yè)務邏輯
_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框架
|