I have 3 classes, The ObjectBody(BodyNode), MainSetupScene(CCLayer), and HudLayer(CCLayer)
I’ve setup ObjectBody and HudLayer in my MainSetupScene and that’s the requirement for it to work.
What i am trying to do now is to add a method where ObjectBody get the privilege to access HudLayer, So the ObjectBody get to access the method created in HudLayer.
3 important points
-ObjectBody is a BodyNode class.
-The method i am trying to access is -(void) located in HudLayer.
-ObjectBody is a b2Body, it calls up the method in HudLayer when Collision is detected.
I did some researches and i came across this, I’ve tried setting up this code in my ObjectBody
HudLayer *hud = [[hud alloc] init];
[self addChild:hud];
[hud NameOfTheMethod];
However BodyNode class doesn’t accept HudLayer as child.
In short, I am trying to make a BodyNode class trigger a method in a CCLayer class.
Don’t try to introduce “knowledge” to objects just to get messages passed across. What I mean by this is that if you have your ObjectBody, HudLayer and MainSetupScene objects (and I’m going to make some assumptions here) designed such that…
MainSetupScene “owns” the HudLayer (for this, you probably did in MainSetupScene
[self addChild:hudLayer];)MainSetupScene “owns” the ObjectBody (again, you probably did in MainSetupScene
[self addChild:objectBody];)Now, you want objectBody to “communicate” with hudLayer. Don’t try to force the knowledge of the hudlayer to the objectbody or vice versa. Just use delegates.
So, for example, in your objectBody you might declare the following
Now, your mainsetupscene would have it’s definition as
Now in your ObjectBody class, when you want to send a message to the hud, use the delegate
[delegate objectBodyStateChanged];Which will be handled by your MainSetupScene. This would then decide to update the HUDLayer by calling the relevant methods and setting appropriate values (which it may get from objectBody).
In short, the body tells the scene that something has happened to make it change. The scene then knows what needs to be updated to reflect that change. The body shouldn’t know that the hud exists and the hud shouldn’t know the body exists.
There’s more to implementing the delegates than I put in here, but if you search around you’ll find lots of details of it.
EDIT AFTER COMMENT
Your protocol is defined in the interface of one class (class A), but the implementation is written in another class (class B). That’s why it’s called delegation – you delegate the work to another class.
You will also need to have a delegate defined and set. So, in class A .h you’d have
In class A .m implementation, you’d have
In class B .h you’d have
Then in the .m implementation, you’d have
There’s lots of better tutorials about delegates that explain it better than this. Hopefully this will make it a bit clearer. You may have used delegates already with UITableView controls and lots of other things in the iOS SDK.