iOS开发iOS学习iOS 开发每天分享优质文章

iOS设计模式之MVC

2017-03-03  本文已影响56人  Jimmy_L_Wang

MVC(Model View ConTroller)
涉及到的三个角色如下:

Model:

模型保存应用程序的数据,定义了怎么去操作它.

The object that holds your application data and defines how to manipulate it.

View:

视图是模型的可视化表示以及用户交互的控件;基本上来说,所有的 UIView对象以及它的子类都属于视图。

The objects that are in charge of the visual representation of the Model and the controls the user can interact with; basically, all the UIViews and their subclasses.

Controller:

控制器是一个协调所有工作的中介者(Mediator)。它访问模型中的数据并在视图中展示它们,同时它还监听事件和根据需要操作数据。

The controller is the mediator that coordinates all the work. It accesses the data from the model and displays it with the views, listens to events and manipulates the data as necessary.

MVC之间的通信方式-如图所示

MVC.png

视图(view)到控制器(controller)的通信:

// add target/action for particular event. you can call this multiple times and you can specify multiple target/actions for a particular event.
添加target/action用于特定的事件,你可以多次调用此方法也可以为某一个特定事件添加多个target/action
// passing in nil as the target goes up the responder chain. The action may optionally include the sender and the event in that order
传入一个nil作为target会使target出现在响应者链里。
// the action cannot be NULL. Note that the target is not retained.action参数不能为NULL。注意target对象不是被持有的。

- (void)addTarget:(nullable id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;

模型到控制器的通信

  1. 通知机制(Notification):控制器注册监听某模型Model数据变化的通知,当此模型Model数据变化后向该控制器controller发送通知,告知模型Model变化情况。
  2. KVO机制(Key-Value Observing):模型Model作为控制器controller的属性,当模型Model属性被修改后,持有此模型Model属性的控制器controller就会检测到数据的改变。
上一篇 下一篇

猜你喜欢

热点阅读