I was wondering how I would go about accessing one instance of a class, say “ship class” across multiple views.
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?
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.
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.
Suppose that class is the app delegate – then, in another file, you’d write something like
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
If this really is one and only one ship object for the whole application, search on stack overflow for advice on creating singleton objects.