一句話就是剝離或輕量化 Controller 中關(guān)于 View 和 Model 的部分。
MVVM 介紹
MVC 有人稱之為 Massive View Controller。
MVC 并沒有做太多事情來解決 iOS 應(yīng)用中日益增長的重量級視圖控制器的問題。在典型的 MVC 應(yīng)用里谱净,許多邏輯被放在 View Controller 里事哭。它們中的一些確實屬于 View Controller钩杰,但更多的是所謂的“表示邏輯(presentation logic)”,以 MVVM 屬術(shù)語來說,就是那些將 Model 數(shù)據(jù)轉(zhuǎn)換為 View 可以呈現(xiàn)的東西的事情,例如將一個 NSDate 轉(zhuǎn)換為一個格式化過的 NSString快集。
![MVVM](http://img.objccn.io//issue-13/mvvm.png)
我們的圖解里缺少某些東西,那些使我們可以把所有表示邏輯放進去的東西廉白。我們打算將其稱為 “View Model” —— 它位于 View/Controller 與 Model 之間:
Model-View-ViewModel 可以:
- MVVM 可以兼容你當下使用的 MVC 架構(gòu)个初。
- MVVM 增加你的應(yīng)用的可測試性。
- MVVM 配合一個綁定機制效果最好猴蹂。
并沒有對我們的 MVC 架構(gòu)做太多改變院溺。還是同樣的代碼,只不過移動了位置磅轻。它與 MVC 兼容珍逸,帶來更輕量的 View Controllers逐虚。
Model 是不可變的,所以我們可以只在初始化的時候指定我們 View Model 的屬性谆膳。對于可變 Model叭爱,我們還需要使用一些綁定機制,這樣 View Model 就能在背后的 Model 改變時更新自身的屬性漱病。此外涤伐,一旦 View Model 上的 Model 發(fā)生改變,那 View 的屬性也需要更新缨称。Model 的改變應(yīng)該級聯(lián)向下通過 View Model 進入 View。
更輕量的 View Controllers
- 把 Data Source 和其他 Protocols 分離出來
- 將 Domain Logic 移到 Model 中
- 創(chuàng)建 Store 類
- 把網(wǎng)絡(luò)請求邏輯移到 Model 層
- 把 View 代碼移到 View 層
我們已經(jīng)看到一些用來創(chuàng)建更小巧的 view controllers 的技術(shù)祝迂。我們并不是想把這些技術(shù)應(yīng)用到每一個可能的角落睦尽,只是我們有一個目標:寫可維護的代碼。知道這些模式后型雳,我們就更有可能把那些笨重的 view controllers 變得更整潔当凡。
延伸閱讀:
-
MVVM
-
Stack Overflow: Model View Controller Store
I will often create a singleton manager class that handles setting up the Core Data stack, and deals with all of the fetching/saving that is involved with the stack. As the quote you mentioned says, this makes it very easy to not only call those methods, but to adjust them if needed, as opposed to having saving/fetching calls all over the place in different view controllers.
Stack Overflow: How to avoid big and clumsy
UITableViewControllers
on iOS