這兩天看斯坦福大學的iOS公開課,講到MVC模式,發現以前理解的有點膚淺。剛好看到唐巧的12年的一片文章里面的片段,順手偷來了。
地址:http://blog.devtang.com/2012/02/05/mvc-in-ios-develop/
正文:
iOS 的 MVC 模式
MVC 模式算是客戶端類程序使用的設計模式的標配了。iOS 對于 Model, View 和 Controller 之間的相互調用有它自己的規范和約定,在公開課的 第一課 中,就介紹了應該如何將 MVC 模式應用在 iOS 開發中。主要的內容就體現在如下這張圖中 (圖片來自該公開課第一課的 配套 pdf 的第 37 頁):
我下面詳細介紹一下這幅圖的意思。
首先圖中綠色的箭頭表示直接引用。直接引用直觀來說,就是說需要包含引用類的申明頭文件和類的實例變量。可以看到,只有 Controller 中,有對 Model 和 View 的直接引用。其中對 View 的直接引用體現為 IBOutlet。
然后我們看 View 是怎么向 Controller 通訊的。對于這個,iOS 中有 3 種常見的模式:
設置 View 對應的 Action Target。如設置 UIButton 的 Touch up inside 的 Action Target。
設置 View 的 delegate,如 UIAlertViewDelegate, UIActionSheetDelegate 等。
設置 View 的 data source, 如 UITableViewDataSource。
通過這 3 種模式,View 達到了既能向 Controller 通訊,又不需要知道具體的 Controller 是誰是目的,這樣就和 Controller 解耦了。
最后我們看 Model。Model 在圖上有一個信號塔類似的圖形,旁邊寫著 Notification & KVO。這表明 Model 主要是通過 Notification 和 KVO 來和 Controller 通訊的。關于 Notification:
// 監聽通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(<#methodName#>) name:kLoginNotification object:nil];
// 取消監聽
[[NSNotificationCenter defaultCenter] removeObserver:self];
// 發送通知
NSDictionary * userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:200] forKey:@"code"];
[[NSNotificationCenter defaultCenter] postNotificationName:<#notification_name#> object:self userInfo:userInfo];