MVC的处理方法

来源:互联网 发布:淘宝开店流程图 编辑:程序博客网 时间:2024/06/06 02:18

iOS 的 MVC 模式

MVC 模式算是客户端类程序使用的设计模式的标配了。iOS 对于 Model, View 和 Controller 之间的相互调用有它自己的规范和约定:

我下面详细介绍一下这幅图的意思。

  • 首先图中绿色的箭头表示直接引用。直接引用直观来说,就是说需要包含引用类的申明头文件和类的实例变量。可以看到,只有 Controller 中,有对 Model 和 View 的直接引用。其中对 View 的直接引用体现为 IBOutlet。

  • 然后我们看 View 是怎么向 Controller 通讯的。对于这个,iOS 中有 3 种常见的模式:

    1. 设置 View 对应的 Action Target。如设置 UIButton 的 Touch up inside 的 Action Target。
    2. 设置 View 的 delegate,如 UIAlertViewDelegate, UIActionSheetDelegate 等。
    3. 设置 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];
    所以,对于初学者,要正确地使用 MVC 模式还是挺难的,回想我们以前做公司某产品 iPhone 版的时候,就有一些 Model 层直接依赖了 Controller 层,比如 Model 层更新数据失败了,直接调用 Controller 层显示出一个失败的提示界面。最后我们做了代码重构,把 Model 的相应改变都用 Notification 来完成,使得在做 开发时轻松了很多。
0 0
原创粉丝点击