1

I came a cross a very nice calculator tutorial for Objective C/iOS. I have thought about this for a long time myself as well and was surprised they way it was implemented. It's very nice and elegant.

The tutorial first sets up calculatorbrain.h and calculatorbrain.m files that are meant to keep track of the calculator stack plus methods handling operations on that stack.

Then it declares a @property instance variable of that calculatorbrain class for the viewcontroller.

My questions is there seems to be a lot of ways to implement this. Why would this way be better?

1) A simple alternative would seem to be just to declare stack and stack methods within the view controller. 2) Instead of declaring it as a @property, why not just create an instance of the calculatorbrain within the view controller.

What are the advantages and disadvantages of the three ways? Which objective programming principle would provide a guideline in choosing which way is preferable?

Thanks.

4

2 回答 2

3

“有不止一种方法可以做到这一点。”

UIViewController虽然它没有在NSViewController.representedObject@property

@interface MyViewController : UIViewController

@property (assign) MyCalculatorModel* model;

@end

如今,借助 ARC 和自动属性合成,您无需指定底层实例变量,这就是您真正需要做的一切。然后,当您创建视图控制器(可能在您的应用程序委托类或其他应用程序级控制器中)时,负责创建视图控制器的控制器使用该属性将模型推送到其中。(注意,它也应该nil在释放视图控制器之前将属性设置为拆卸。)

您的选项 #1 不太理想,因为它将非视图代码与特定于视图的代码结合在一起。您的选项#2 不太理想,因为它意味着视图控制器负责以某种方式获取模型并将其放入私有实例变量本身,这可以说是控制反转。(即,您希望视图控制器外部的东西推入模型,但不能因为实例变量默认是私有的)

于 2013-06-15T15:56:44.530 回答
2

将逻辑与接口分离通常是一种很好的做法。

例如,如果您决定创建另一个 ViewController 并从原来的 ViewController 过渡到它,并且您需要在那里的计算数据(例如,如果您想绘制图表),您只需将您的计算器大脑传递给第二个视图控制器。

您可以在此处阅读有关 Cocoa 框架中使用的设计模式的更多信息(同样的原则适用于 Cocoa Touch):Cocoa 设计模式

这是一个 Apple 教程,它提供了一个经过深思熟虑但简单的 MVC 模式应用程序示例: 您的第二个 iOS 应用程序

您可以在网上搜索有关 MVC(模型-视图-控制器)的更多信息。

于 2013-06-15T15:56:36.623 回答