1.mvc和mvvm的由來
iOS中饲鄙,我們使用的大部分都是[MVC架構](http://www.reibang.com/p/518cb07679eb)
雖然MVC的層次明確,但是由于功能日益的增加圆雁,代碼的維護忍级,
更多的代碼被寫在了Controller中,這樣Controller就顯得非常臃腫摸柄。
為了給Controller瘦身颤练,后來又從MVC衍生出了一種新的架構模式MVVM架構
2.mvvm的概念
Model-數(shù)據(jù)層
ViewController/View-展示層
ViewModel- 數(shù)據(jù)模型
3.mvc和mvvm的區(qū)別
首先我們簡化一下MVC的架構模式圖:
![1.png](http://upload-images.jianshu.io/upload_images/2182103-e2e8b9f26354e07e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
mvc.png
在這里,Controller需要做太多得事情驱负,表示邏輯嗦玖、業(yè)務邏輯,所以代碼量非常的大跃脊。而MVVM:
MVVM模式和MVC模式一樣宇挫,目的主要分離的英文
(視圖)和模型(模型),有以下四大優(yōu)點
1.低耦合
視圖(視圖)可以獨立于模型變化和修改酪术,一個視圖模型可以綁定到不同的“查看”上器瘪,當查看變化的時候模型可以不變,當模型變化的時候視圖也可以不變绘雁。
2 .可重用性
你可以把一些視圖邏輯放在一個ViewModel里面橡疼,讓很多視圖重用這段視圖邏輯
3.獨立開發(fā)
開發(fā)人員可以專注于業(yè)務邏輯和數(shù)據(jù)的開發(fā)(ViewModel),設計人員可以專注在頁面設計中庐舟,使用Expression Blend可以很容易設計界面并生成xaml代碼
4.可測試
界面素來是比較難于測試的欣除,而現(xiàn)在測試可以針對ViewModel來寫。
4.MVVM的實踐
1.model層的代碼:
#import <Foundation/Foundation.h>
@interface CustomModel : NSObject
@property (nonatomic,strong)NSString *title;
@end
2.view層代碼:(創(chuàng)建一個cell)
<1>CustomTableViewCell.h的代碼
#import <UIKit/UIKit.h>
@interface CustomTableViewCell : UITableViewCell
@property (nonatomic,strong)UILabel *titleLabel;
@end
<2>CustomTableViewCell.m的代碼
#import "CustomTableViewCell.h"
@implementation CustomTableViewCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
_titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 50)];
[self.contentView addSubview:_titleLabel];
_titleLabel.backgroundColor = [UIColor whiteColor];
_titleLabel.font = [UIFont systemFontOfSize:15];
_titleLabel.textAlignment = NSTextAlignmentCenter;
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end
3.關鍵的ViewModel