ios - 什么应该拥有 MVC 模式中的模型?

标签 ios objective-c oop model-view-controller

从我记事起,我就一直在开发 iOS 应用程序,但直到最近获得实习编程时,我的编程风格才成熟很多。我很早就学习了很多 OO 概念,因为我意识到如果不理解它们,生活就会很糟糕,但我从未让自己学习的一件事是 MVC 模式。

为了提供上下文,假设我在单个 SolarSystemView(UIView 的子类)中绘制一个太阳系。我的 SolarSystemView 应该有一个 SolarSystem 类的实例变量(一个包含具有所有重要行星和恒星属性的数据结构的类),还是应该属于一个SolarSystemViewController 的实例?还是完全不同的东西?我找不到任何给出满意答案的示例代码。

我想如果 View 拥有模型,操作会非常顺畅,但这也不是很好的风格。毕竟,SolarSystem 实例必须以某种方式动态变化,并且与 SolarSystemView 更新的速率相同或相似。

最佳答案

在 MVC 范式中,模型应该与 View 分离。为了获得它自己绘制所需的数据,它向 Controller 请求它,而 Controller 又向 Model 请求它。这样,我们就可以将信息与 GUI 分离。如果有帮助,请将其视为模型 Controller View 。因此,在大多数情况下, Controller “拥有”模型。

例如,在 cs193p 中,CalculatorViewController( Controller )有一个 CalculatorBrain(模型)属性,它与之交互以获得方程的结果以显示在查看。

在您的特定示例中,SolarSystemViewController 可能对 SolarSystem 有很强的引用,它会轮询将传递给 的数据SolarSystemView 以便它可以在需要更新时自行绘制。 SolarSystemView 还可能会在用户与其交互时通知 SolarSystemViewController,以便它可以显示其他 View 或更新 SolarSystem,以及任何其他任务它可以执行。

请注意,Cocoa 和 Cocoa Touch 中的 MVC 范例与在其他地方看到的更通用的 MVC 版本(如 Smalltalk)略有不同。例如,如果您查看 Wikipedia page on MVC那里的图表应该看起来与你一直在学习的不同。事实上,GoF(Design Patterns)就是这样描述MVC的。

MVC consists of three kinds of objects. The Model is the application object, the View is its screen presentation, and the Controller defines the way the user interface reacts to user input. Before MVC, user interface designs tended to lump these objects together. MVC decouples them to increase flexibility and reuse. MVC decouples views and models by establishing a subscribe/notify protocol between them. A view must ensure that its appearance reflects the state of the model. Whenever the model's data changes, the model notifies views that depend on it. In response, each view gets an opportunity to update itself. This approach lets you attach multiple views to a model to provide different presentations. You can also create new views for a model without rewriting it.

在这两种情况下,模型本身都在联系 View 以更新它。然而,在 iOS 上,模型和 View 之间的交互是通过 Controller 处理的。这在 first session of cs193p 中得到了很好的解释。以及Apple's own documentation on MVC relationships.这样,您只需重写 Controller 代码即可在其他地方重用模型和 View 。

这里是来自 cs193p 的 MVC 图来澄清。

Model View Controller

关于ios - 什么应该拥有 MVC 模式中的模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15453490/

相关文章:

Python 创建对象

ios - 如何删除子托管对象上下文上的临时对象?

ios - 如何从字符串中识别 UTF-8 编码的文本并将其转换为 Swift 中的笑脸\表情符号

ios - 不要停止 XCTAssertThrowsSpecific 上的测试执行

objective-c - iOS UIWebView、CSS & 和百分比

ios - 改变 alpha 会改变颜色

ios - iOS中的3des加密解密

c++ - 覆盖运算符 = 以便我们可以使用 = 复制类实例而不会出现浅拷贝问题

objective-c - 读取PNG注释(未压缩的zTXt数据)

oop - 从 smalltalk (squeak) 中的字符串中提取子字符串