iOS MVC

作者: Roy_Gao | 来源:发表于2016-04-13 15:16 被阅读601次

    这两天看斯坦福大学的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];

    相关文章

      网友评论

          本文标题:iOS MVC

          本文链接:https://www.haomeiwen.com/subject/roowlttx.html