1、MVC设计模式
mv1.pngModel 呈现数据,View 呈现用户界面,而 View Controller 调节它两者之间的交互
弊端
没有做太多事情来解决 iOS 应用中日益增长的重量级视图控制器的问题。在典型的 MVC 应用里,许多逻辑被放在 View Controller 里。它们中的一些确实属于 View Controller,但更多的是所谓的“表示逻辑(presentation logic)”
2、MVVM设计模式,即M-V-VM
mv2.png本质就是那些将 Model 数据转换为 View 可以呈现的东西的事情,例如将一个 NSDate 转换为一个格式化过的 NSString
这个图解准确地描述了什么是 MVVM:一个 MVC 的增强版,我们正式连接了视图和控制器,并将表示逻辑从 Controller 移出放到一个新的对象里,即 View Model。MVVM 听起来很复杂,但它本质上就是一个精心优化的 MVC 架构。
3、优点
- MVVM 可以兼容你当下使用的 MVC 架构。
- MVVM 增加你的应用的可测试性。
- MVVM 配合一个绑定机制效果最好。
4、Demo
模型person
.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
- (instancetype)initWithFirstName:(NSString *)firstName
lastName:(NSString *)lastName
birthdate:(NSDate *)birthdate;
@property (nonatomic, readonly) NSString *firstName;
@property (nonatomic, readonly) NSString *lastName;
@property (nonatomic, readonly) NSDate *birthdate;
@end
.m
#import "Person.h"
@implementation Person
- (instancetype)initWithFirstName:(NSString *)firstName lastName:(NSString *)lastName birthdate:(NSDate *)birthdate
{
if (self = [super init]) {
_firstName = firstName;
_lastName = lastName;
_birthdate = birthdate;
}
return self;
}
@end
模型视图层PersonViewModel
.h
#import <Foundation/Foundation.h>
#import "Person.h"
@interface PersonViewModel : NSObject
@property (nonatomic, strong) Person *person;
@property (nonatomic, copy) NSString *nameText;
@property (nonatomic, copy) NSString *birthdateText;
@end
.m
#import "PersonViewModel.h"
@implementation PersonViewModel
- (void)setPerson:(Person *)person
{
_person = person;
_nameText = [NSString stringWithFormat:@"%@%@",person.firstName,person.lastName];
NSDateFormatter *format = [[NSDateFormatter alloc]init];
# [format setDateFormat:@"yyyy-MM-dd,HH:mm:ss,EEEE"];
_birthdateText = [format stringFromDate:person.birthdate];
}
@end
控制器层ViewController
#import "ViewController.h"
#import "Person.h"
#import "PersonViewModel.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *Name;
@property (weak, nonatomic) IBOutlet UILabel *birthday;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//创建-M
Person *model = [[Person alloc]initWithFirstName:@"One" lastName:@"cat" birthdate:[[NSDate alloc]init]];
//创建-VM
PersonViewModel *viewModel = [[PersonViewModel alloc]init];
viewModel.person = model;
//设置-V
self.Name.text = viewModel.nameText;
self.birthday.text = viewModel.birthdateText;
}
@end
view.png
网友评论