[iOS]MVVM-架構介紹,iosmvvm-架構介紹

來源:互聯網
上載者:User

[iOS]MVVM-架構介紹,iosmvvm-架構介紹
  

我於 2011 年在 500px 找到自己的第一份 iOS 開發工作。雖然我已經在大學裡做了好幾年 iOS 外包開發,但這才是我的一個真正的 iOS 開發工作。我被作為唯一的 iOS 開發人員被招聘去實現擁有漂亮設計的 iPad 應用。在短短七周裡,我們就發布了 1.0 並持續迭代,添加了更多特性,但從本質上,程式碼程式庫也變得更加複雜了。

有時我感覺就像我不知道在做什麼。雖然我知道自己的設計模式——就像任何好的編程人員那樣 —— 但我太接近我在做的產品以至於不能客觀地衡量我的架構決策的有效性。當隊伍中來了另外一位開發人員時,我意識到我們陷入困境了。

從沒聽過 MVC ?有人稱之為 Massive View Controller(重量級視圖控制器),這就是我們那時候的感覺。我不打算介紹令人汗顏的細節,但說實在的,如果我不得不再次重來一次,我絕對會做出不同的決策。

我會修改一個關鍵架構,並將其帶入我從那時起就在開發的各種應用,即使用一種叫做 Model-View-ViewModel 的架構替換 Model-View-Controller。

所以,MVVM 到底是什嗎?與其專註於說明 MVVM 的來曆,不如讓我們看一個典型的 iOS 是如何構建的,並從那裡瞭解 MVVM:

我們看到的是一個典型的 MVC 設定。Model 呈現資料,View 呈現使用者介面,而 View Controller 調節它兩者之間的互動。Cool!

稍微考慮一下,雖然 View 和 View Controller 是技術上不同的組件,但它們幾乎總是手牽手在一起,成對的。你什麼時候看到一個 View 能夠與不同 View Controller 配對?或者反過來?所以,為什麼不正規化它們的串連呢?

這更準確地描述了你可能已經編寫的 MVC 代碼。但它並沒有做太多事情來解決 iOS 應用中日益增長的重量級視圖控制器的問題。在典型的 MVC 應用裡,許多邏輯被放在 View Controller 裡。它們中的一些確實屬於 View Controller,但更多的是所謂的“表示邏輯(presentation logic)”,以 MVVM 屬術語來說,就是那些將 Model 資料轉換為 View 可以呈現的東西的事情,例如將一個 NSDate 轉換為一個格式化過的 NSString。

我們的圖解裡缺少某些東西,那些使我們可以把所有表示邏輯放進去的東西。我們打算將其稱為 “View Model” —— 它位於 View/Controller 與 Model 之間:

看起好多了!這個圖解準確地描述了什麼是 MVVM:一個 MVC 的增強版,我們正式串連了視圖和控制器,並將表示邏輯從 Controller 移出放到一個新的對象裡,即 View Model。MVVM 聽起來很複雜,但它本質上就是一個精心最佳化的 MVC 架構,而 MVC 你早已熟悉。

現在我們知道了什麼是 MVVM,但為什麼我們會想要去使用它呢?在 iOS 上使用 MVVM 的動機,對我來說,無論如何,就是它能減少 View Controller 的複雜性並使得表示邏輯更易於測試。通過一些例子,我們將看到它如何達到這些目標。

此處有三個重點是我希望你看完本文能帶走的:

MVVM 可以相容你當下使用的 MVC 架構。
MVVM 增加你的應用的可測試性。
MVVM 配合一個綁定機制效果最好。
如我們之前所見,MVVM 基本上就是 MVC 的改進版,所以很容易就能看到它如何被整合到現有使用典型 MVC 架構的應用中。讓我們看一個簡單的 Person Model 以及相應的 View Controller:

1
2
3
4
5
6
7
8
9
10
@interface Person : NSObject

- (instancetype)initwithSalutation:(NSString *)salutation firstName:(NSString *)firstName lastName:(NSString *)lastName birthdate:(NSDate *)birthdate;

@property (nonatomic, readonly) NSString *salutation;
@property (nonatomic, readonly) NSString *firstName;
@property (nonatomic, readonly) NSString *lastName;
@property (nonatomic, readonly) NSDate *birthdate;

@end

 

Cool!現在我們假設我們有一個 PersonViewController ,在 viewDidLoad 裡,只需要基於它的 model 屬性設定一些 Label 即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
- (void)viewDidLoad {
[super viewDidLoad];

if (self.model.salutation.length > 0) {
self.nameLabel.text = [NSString stringWithFormat:@"%@ %@ %@", self.model.salutation, self.model.firstName, self.model.lastName];
} else {
self.nameLabel.text = [NSString stringWithFormat:@"%@ %@", self.model.firstName, self.model.lastName];
}

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE MMMM d, yyyy"];
self.birthdateLabel.text = [dateFormatter stringFromDate:model.birthdate];
}

 

這全都直截了當,標準的 MVC。現在來看看我們如何用一個 View Model 來增強它。

1
2
3
4
5
6
7
8
9
10
@interface PersonViewModel : NSObject

- (instancetype)initWithPerson:(Person *)person;

@property (nonatomic, readonly) Person *person;

@property (nonatomic, readonly) NSString *nameText;
@property (nonatomic, readonly) NSString *birthdateText;

@end

 

我們的 View Model 的實現大概如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@implementation PersonViewModel

- (instancetype)initWithPerson:(Person *)person {
self = [super init];
if (!self) return nil;

_person = person;
if (person.salutation.length > 0) {
_nameText = [NSString stringWithFormat:@"%@ %@ %@", self.person.salutation, self.person.firstName, self.person.lastName];
} else {
_nameText = [NSString stringWithFormat:@"%@ %@", self.person.firstName, self.person.lastName];
}

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE MMMM d, yyyy"];
_birthdateText = [dateFormatter stringFromDate:person.birthdate];

return self;
}

@end

 

Cool!我們已經將 viewDidLoad 中的表示邏輯放入我們的 View Model 裡了。此時,我們新的 viewDidLoad 就會非常輕量:

1
2
3
4
5
6
- (void)viewDidLoad {
[super viewDidLoad];

self.nameLabel.text = self.viewModel.nameText;
self.birthdateLabel.text = self.viewModel.birthdateText;
}

 

所以,如你所見,並沒有對我們的 MVC 架構做太多改變。還是同樣的代碼,只不過移動了位置。它與 MVC 相容,帶來更輕量的 View Controllers。

可測試,嗯?是怎樣?好吧,View Controller 是出了名的難以測試,因為它們做了太多事情。在 MVVM 裡,我們試著儘可能多的將代碼移入 View Model 裡。測試 View Controller 就變得容易多了,因為它們不再做一大堆事情,並且 View Model 也非常易於測試。讓我們來看看:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
SpecBegin(Person)
NSString *salutation = @"Dr.";
NSString *firstName = @"first";
NSString *lastName = @"last";
NSDate *birthdate = [NSDate dateWithTimeIntervalSince1970:0];

it (@"should use the salutation available. ", ^{
Person *person = [[Person alloc] initWithSalutation:salutation firstName:firstName lastName:lastName birthdate:birthdate];
PersonViewModel *viewModel = [[PersonViewModel alloc] initWithPerson:person];
expect(viewModel.nameText).to.equal(@"Dr. first last");
});

it (@"should not use an unavailable salutation. ", ^{
Person *person = [[Person alloc] initWithSalutation:nil firstName:firstName lastName:lastName birthdate:birthdate];
PersonViewModel *viewModel = [[PersonViewModel alloc] initWithPerson:person];
expect(viewModel.nameText).to.equal(@"first last");
});

it (@"should use the correct date format. ", ^{
Person *person = [[Person alloc] initWithSalutation:nil firstName:firstName lastName:lastName birthdate:birthdate];
PersonViewModel *viewModel = [[PersonViewModel alloc] initWithPerson:person];
expect(viewModel.birthdateText).to.equal(@"Thursday January 1, 1970");
});
SpecEnd

 

如果我們沒有將這個邏輯移入 View Model,我們將不得不執行個體化一個完整的 View Controller 以及伴隨的 View,然後去比較我們 View 中 Lable 的值。這樣做不只是會變成一個麻煩的間接層,而且它只代表了一個十分脆弱的測試。現在,我們可以按意願自由地修改視圖層級而不必擔心破壞我們的單元測試。使用 MVVM 帶來的對於測試的好處非常清晰,甚至從這個簡單的例子來看也可見一斑,而在有更複雜的表示邏輯的情況下,這個好處會更加明顯。

注意到在這個簡單的例子中, Model 是不可變的,所以我們可以只在初始化的時候指定我們 View Model 的屬性。對於可變 Model,我們還需要使用一些綁定機制,這樣 View Model 就能在背後的 Model 改變時更新自身的屬性。此外,一旦 View Model 上的 Model 發生改變,那 View 的屬性也需要更新。Model 的改變應該級聯向下通過 View Model 進入 View。

在 OS X 上,我們可以使用 Cocoa 綁定,但在 iOS 上我們並沒有這樣好的配置可用。我們想到了 KVO(Key-Value Observation),而且它確實做了很偉大的工作。然而,對於一個簡單的綁定都需要很大的樣板代碼,更不用說有許多屬性需要綁定了。作為替代,我個人喜歡使用 ReactiveCocoa,但 MVVM 並未強制我們使用 ReactiveCocoa。MVVM 是一個偉大的典範,它自身獨立,只是在有一個良好的綁定架構時做得更好。

我們覆蓋了不少內容:從普通的 MVC 派生出 MVVM,看它們是如何相相容的範式,從一個可測試的例子觀察 MVVM,並看到 MVVM 在有一個配對的綁定機制時工作得更好。如果你有興趣學習

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.