MVC的处理方法

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 来完成,使得在做 开发时轻松了很多。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值