談到 iOS 的架構模式,多數人第一個想到的就是 MVC。但如果仔細觀察一段時間的專案,你會發現 ViewController 往往膨脹成難以維護的巨物。本文把 MVC、MVP、MVVM 三者放在一起對照,釐清各自的職責邊界。

三者的定位:
在 Apple 的定義裡,Controller 可以直接存取 Model,也可以直接控制 View;但 Model 與 View 之間不能直接通訊。
View 透過 target-action 機制把事件交給 Controller,例如我們在 Storyboard 中把 UIButton 拖進程式碼所產生的 @IBAction:使用者點擊按鈕,View 就把這個訊息傳給 Controller。
若 Controller 需要即時掌握 View 的狀態變化,它會透過 protocol 把自己設為 View 的 delegate,於是 View 在 will change、should change、did change 時都能通知到 Controller。View 本身不儲存資料,它展示的內容來自 Controller 整理後的結果,而非直接取自 Model。
Model 刻意與 UI 解耦,因此不能反向依賴 Controller。當 Model 發生變化需要通知外部時,通常採用廣播機制,iOS 中最常見的是 NSNotification 與 KVO。
NSNotification:
let center = NSNotificationCenter.defaultCenter()
center.addObserverForName(UIContentSizeCategoryDidChangeNotification,
object: UIApplication.sharedApplication(),
queue: NSOperationQueue.mainQueue()) { notification in
let c = notification.userInfo?[UIContentSizeCategoryNewValueKey]
}
其中 UIContentSizeCategoryDidChangeNotification 與 UIContentSizeCategoryNewValueKey 都是系統預先定義好的字串常數。
KVO:
// viewDidLoad 中註冊觀察
webView.addObserver(self, forKeyPath: "estimatedProgress",
options: .New, context: nil)
override func observeValueForKeyPath(keyPath: String?,
ofObject object: AnyObject?,
change: [NSObject : AnyObject]?,
context: UnsafeMutablePointer<Void>) {
if keyPath == "estimatedProgress" {
progressView.hidden = webView.estimatedProgress == 1
progressView.setProgress(Float(webView.estimatedProgress), animated: true)
}
}
MVP 由經典 MVC 演變而來,把 Controller 替換為 Presenter。依維基與各家說法,MVP 相較 MVC 的核心優勢是「Model 與 View 完全分離」,兩者的資訊傳遞只能透過 Presenter。
我查過資料,其他平台上「View 能否直接與 Model 通訊」其實有不同說法,但在 iOS 開發的語境下,Apple 的定義是明確的:所有物件都被歸類為 model、view 或 controller 之一;Model 持有資料,View 負責顯示與互動,View Controller 居中協調。因此我個人在 iOS 專案中一律按「Model 與 View 不可直接通訊」來理解與實作。

上圖對比了 MVVM 與 MVC 的差異。
在典型的 MVC 寫法中,Controller 承接了太多責任,視圖處理邏輯與業務邏輯全塞在一起:

MVVM 的做法是把視圖處理邏輯從 Controller 剝離出去交給 View,剩下的業務邏輯則獨立成 ViewModel。這樣做有兩個直接好處:
實作時,我們應該為 app delegate 中的根視圖建立一個 ViewModel;而當需要呈現下一層的 ViewController 時,則以目前的 ViewModel 為基礎,為它建立一個子 ViewModel。

關鍵在於:這些 ViewModel 的程式碼不該寫在 ViewController 裡。View 向自己的 ViewModel 索取所需資料,而 ViewController 完全歸屬於 View 那一層,只負責把資料渲染到畫面上。