views:

903

answers:

3

I have a class called GameScene, with is a subclass of a cocos2d Scene.

In there I have two layers. GameLayer and ControlsLayer. You can probably tell already that I want the ControlsLayer to move stuff around in the GameLayer. To be precise, I'm trying to control a cPBody in the GameLayer from the ControlsLayer.

At the moment, I'm trying to route the instructions from the ControlsLayer, back up into the GameScene and then back down into the GameLayer. If that makes sense. Anyway, I can't get it to work. I have a PHP background so I think I'm incorrectly applying my PHP experience to Obj-C.

My thinking is, I should be able to access a property inside a class/object using something like

aThing *someThing = someInstance->aThing;

From the sample code I've been looking at, it looks like this should work. But it doesn't. Here's the code, stripped down to as much as possible http://pastebin.com/d49c9d0be

Rather than knowing how to fix this particular issue, The question is, what don't I understand?

+3  A: 

In Objective-C you need to define accessor methods to get at the instance variable, you can't directly access it like that unless you're calling it from the same class type (for instance when you're implementing the NSCopying protocol and need to set private variables, but don't worry about that now).

The easiest way to do that is to define a property in your header using @property(retain) SomeClass *name;, and have Objective-C generate it by putting @synthesize name = instanceVariable; in your implementation. You can then access the variable outside of that class using object.name; or [object name];. For more information take a look in the documentation for properties and Object Oriented programming.

Marc Charbonneau
Keep in mind that if you declare @property(retain) SomeClass * name you will also have to [release name] in your -(void)dealloc method
e.James
+1  A: 

You're not exposing the gameLayer.myBody property in any shape. You'd have to use the @property declaration (assuming objective-c 2.0) (here's an example).

I don't have any PHP background, so I don't know how it may be different in PHP.

Jonas
+1  A: 

The correct way to access a property in an object is as follows:

aThing * someThing = someInstance.aThing; // new style

or

aThing * someThing = [someInstance aThing]; // old style

If you were coding in c, the -> operator would make sense. In objective-c, however, objects are always passed around through pointers. No objective-c variable ever actually holds an object, they just hold pointers to objects. The language designers simply decided to use the [] or . syntax to access members, so that's what we have to do!

e.James