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的负担,使功能划分更加合理。