iOS / Cocoa - 数据模型的设计模式< - >控制器 [英] iOS/Cocoa - Design Pattern for Data Model <-> Controller

查看:159
本文介绍了iOS / Cocoa - 数据模型的设计模式< - >控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(我已经阅读了很多stackoverflow的帖子,一般来说,Cocoa MVC,但是大多数涉及视图控制器之间的信息共享。)






  • DataModel类负责下载,解析,验证和存储(XML或JSON派生)数据, p>


  • 一个ViewController类,它将实例化一个DataModel对象,并需要随时间从DataModel获取信息(例如更新视图以反映模型中的更改)




Q。处理模型数据更改的通知,并将数据提供给View控制器,最好的做法是什么?



方法我见过include:




  • Model类发布通知,在Notification的userInfo字典中提供数据。 View Controller监听通知,查看userInfo。例如Apple的SeismicXML示例代码。


  • Model类定义了一个协议,View Controller作为代理,响应Model的特定协议方法。 p>


  • Model类保留了一个指向View Controller的指针,直接调用View Controller中的方法或属性。 (不是这个的风扇,我必须说,因为它需要模型和控制器之间的紧密绑定。)




解决方案

我会避免在其他人的意见。所有具有模型的成本存储指向视图控制器的指针。这是正常职责的倒转。在MVC中,模型应该独立于任何控制器。



代理/协议模式适用于在视图控制器的生命周期内创建和销毁的短期模型。



通知和KVO是我处理底层模型更改的主要方式。它允许模型生存很长时间,独立于在其生命周期中创建和销毁的控制器。


(I have read many stackoverflow posts on this, and Cocoa MVC in general, but most relate to the sharing of information between View Controllers.)

Given the following:

  • a DataModel class responsible for the downloading, parsing, verification and storage of (XML or JSON derived) data,

  • a ViewController class, which will instantiate a single DataModel object, and will need to get information from that DataModel over time (e.g. updating views to reflect changes in the Model)

Q. What is the best practice for handling the notification of model data changes, and the supply of that data to the View Controller?

Approaches I've seen include:

  • the Model class posts Notifications, supplying the data in the Notification's userInfo dictionary. The View Controller listens for the Notifications, looks at the userInfo. e.g. Apple's SeismicXML sample code.

  • the Model class defines a Protocol, and the View Controller acts as the delegate, responding to specific protocol methods of the Model.

  • the Model class keeps a pointer to the View Controller, calls methods or properties in the View Controller directly. (Not a fan of this one, I must say, as it requires tight binding between the Model and Controller.)

I'm leaning towards the Notification approach, but would like to hear the views of other people.

解决方案

I would avoid at all costs having the model store pointers to the view controller. This is an inversion of the normal responsibilities. In MVC, the model should act independently of any controller.

The delegate/protocol pattern works well for short lived models that are created and destroyed within the lifecycle of the view controller.

Notifications and KVO are the primary way I handle underlying model changes. It allows for the model to live a long time and work independent of controllers that are created and destroyed during it's lifetime.

这篇关于iOS / Cocoa - 数据模型的设计模式< - >控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆