Cocoa Touch中多个视图中的一个实例 [英] One instance across multiple views in Cocoa Touch

查看:67
本文介绍了Cocoa Touch中多个视图中的一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何访问一个类的实例,即在多个视图之间访问船级。

I was wondering how I would go about accessing one instance of a class, say "ship class" across multiple views.

说我有一个rootViewController和三个副视图,一场主战,一场战斗,一场登陆。我将在哪里确切地实现一个类的实例,该实例将所有信息存储在我的船上并通过其他视图进行访问。如果我的飞船只剩下x枚导弹,那么另一个视图如何访问该信息以显示它。如果我在主视图上实现它,那么着陆视图如何获取该信息?

Lets say I have a rootViewController and three subviews, one Main, one battle, and one landing. Where exactly would I implement an instance of a class that stores all the information on my ship and access it though the other views. If my ship has x missiles left, how does another view access that information to display it. If I implement it on the Main view how does the landing view get that info?

我知道必须有一种简单的方法来做到这一点,我敢打赌,有一种方法应该在不实现任何船舶等级的情况下做到这一点本身的意见。不过,对于iPhone编程我还是很陌生。

I know there has to be an easy way to do this, and I bet there is a way you are supposed to do it without implementing the ship class in any of the views per se. I am still fairly new to programming for the iPhone though.

在此先感谢大家提供的任何帮助。

Thank you in advance for any help you all may provide.

推荐答案

创建了Ship类的单个实例后,您需要告诉其他视图该实例是什么。因此,您可以将Ship设为创建它的类的公共属性。

Once you have created the single instance of your Ship class, you need to tell any other views what that instance is. So you could make Ship a public property on the class that created it.

@property (nonatomic, retain) Ship* myShip;

假设该类是应用程序委托-然后,在另一个文件中,您将编写类似

Suppose that class is the app delegate - then, in another file, you'd write something like

[[[UIApplication sharedApplication] delegate].myShip getNumberOfMasts];

这很简单,适用于简单的项目,但是它确实使Ship对象可用于任何对象文件中的文件-它有效地变成了全局数据,在大型项目中可能很难调试。 (如果myShip发生了问题,哪个对象负责?如果它可以是您应用中的任何对象,那么与将访问权限限制在需要它的两个类相比,这是一个更难调试的问题。)想要限制对船的访问,那么不要将myShip设置为公共属性-而是让创建myShip的对象在初始化调用中创建需要访问的其他对象时将其传递给它。

This is simple, and works for a simple project, but it does make the Ship object available to any file in your project - it effectively becomes global data, which can be hard to debug in a larger project. (If something bad is happening to myShip, which object was responsible? If it could be any object in your app, then this is a harder problem to debug than if access is restricted to the two classes that need it.) So, if you want to restrict access to ship, then don't make myShip a public property - instead have the object that created myShip pass it in initialisation calls when it creates other objects that need access. Something like this

[[myBattleController alloc] initWithShip:myShip];

如果这确实是整个应用程序中的唯一对象,请在堆栈上搜索以获取建议关于创建单例对象。

If this really is one and only one ship object for the whole application, search on stack overflow for advice on creating singleton objects.

这篇关于Cocoa Touch中多个视图中的一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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