IOS的MVC和MVVM模式簡明介紹

iOS中的MVC(Model-View-Controller)將軟件系統分爲Model、View、Controller三部分,結構圖以下:web

Model: 你的應用本質上是什麼(但不是它的展現方式)
Controller:你的Model怎樣展現給用戶(UI邏輯)
View:用戶看到的,被Controller操縱着的
 
Controller能夠直接訪問Model,也能夠直接控制View。
但Model和View不能互相通訊。
 
View能夠經過action-target的方式訪問Controller,好比咱們在StoryBoard中拖UIButton到代碼中所建立的@IBAction,當按鈕被點擊時,View就會傳遞該信息給Controller。
有時候Controller須要實時監控View的狀態,這時Controller會經過protocol將其自身設爲View的delegate,這樣當View will change、should change、did change 的時候Controller也會接到相應通知。
View不存儲數據,但View能夠經過協議獲取Controller而不是Model中的數據用來展現。
Controller整理Model中的數據用於給View展現。
 
Model不能直接與Controller通信,由於Model是獨立於UI存在的。
但當Model發生改變想通知Controller時可以使用廣播機制,在iOS中有NSNotification和KVO(Key-value observing)可供使用。
NSNotification:
1  let center = NSNotificationCenter.defaultCenter()
2         
3         center.addObserverForName(UIContentSizeCategoryDidChangeNotification,
4             object: UIApplication.sharedApplication(),
5             queue: NSOperationQueue.mainQueue())
6             { notification in
7                 let c = notification.userInfo?[UIContentSizeCategoryNewValueKey]
8         }

KVO:ide

1   webView.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil)
2 
3      override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSObject : AnyObject]?, context: UnsafeMutablePointer<Void>) {
4              if (keyPath == "estimatedProgress") {
5                  progressView.hidden = webView.estimatedProgress == 1
6                  progressView.setProgress(Float(webView.estimatedProgress), animated: true)
7              }
8          }
MVP模式從經典的MVC模式演變而來,將Controller替換成Presenter,依據MVP百度百科中的解釋,MVP的優勢相比較於MVC是徹底分離Model與View,Model與View的信息傳遞只能經過Controller/Presenter,我查閱資料發如今其餘平臺上的MVC模式View與Model可否直接通信有着不一樣的說法,但在iOS開發中,Apple是這麼說的。在MVC下,全部的對象被歸類爲一個model,一個view,或一個controller。Model持有數據,View顯示與用戶交互的界面,而View Controller調解Model和View之間的交互,在iOS開發中我按照Model與View沒法相互通信來理解。
 
MVVM(Model View View-Model)
上圖展現了MVVM與MVC的差異。
 
在MVC模式的iOS開發中,Controller承擔了太多的代碼,包含着咱們的視圖處理邏輯和業務邏輯。
在MVVM中,咱們將視圖處理邏輯從C中剝離出來給V,剩下的業務邏輯部分被稱作View-Model。
使用MVVM模式的iOS應用的可測試性要好於MVC,由於ViewModel中並不包含對View的更新,相比於MVC,減輕了Controller的負擔,使功能劃分更加合理。
相關文章
相關標籤/搜索