The sprite kit reference guide mentions the double dispatch pattern and refers to this wikipedia article.
It's not entirely clear to me how to implement this double dispatch pattern.
As far as I understand it: You have two objects. You call the first object with a reference to the second object as a parameter. You end up in a different function based on the type of the second object. Based on the function you are in, you call a method on the second object.
Some code should make it easier to understand. Suppose I have two custom classes A and B.
Keep in mind that you don't know (and don't have to know) which classes your objects have.
You also don't know which is the first or second object in the contact.
implementation of A:
implementation of B:
But of course this code will not work because objective -c doesn't look at the argument types. It just sees twice didBeginContact:with: in both classes.
My question: how is double dispatch implemented? What am I missing here?
It's not entirely clear to me how to implement this double dispatch pattern.
As far as I understand it: You have two objects. You call the first object with a reference to the second object as a parameter. You end up in a different function based on the type of the second object. Based on the function you are in, you call a method on the second object.
Some code should make it easier to understand. Suppose I have two custom classes A and B.
Keep in mind that you don't know (and don't have to know) which classes your objects have.
You also don't know which is the first or second object in the contact.
Code:
-(void) didBeginContact:(SKPhysicsContact *)contact
{
SKNode *firstNode = contact.bodyA.node; //could be class A or B
SKNode *secondNode = contact.bodyB.node; //could be class A or B
[firstNode didBeginContact:contact
with:&secondNode];
}
implementation of A:
Code:
-(void) didBeginContact:(SKPhysicsContact *) contact
with:(ClassA **) node
{
// class A with A contact => do nothing
}
-(void) didBeginContact:(SKPhysicsContact *) contact
with:(ClassB **) node
{
// class A with B contact => reverse course of A and B
[self reverseCourse];
[*node reverseCourse];
}
implementation of B:
Code:
-(void) didBeginContact:(SKPhysicsContact *) contact
with:(ClassA **) node
{
// class B with A contact => reverse course of A and B
[self reverseCourse];
[*node reverseCourse];
}
-(void) didBeginContact:(SKPhysicsContact *) contact
with:(ClassB **) node
{
// class B with B contact => explode both objects
[self explode];
[*node explode];
}
But of course this code will not work because objective -c doesn't look at the argument types. It just sees twice didBeginContact:with: in both classes.
My question: how is double dispatch implemented? What am I missing here?