Hi,
How to implement delegation in cocos2dx ? In objective C , we use protocols now i want to do the same in cocos2dx but not able to find a way to implement the same .
Please help Thanks in advance!
Hi,
How to implement delegation in cocos2dx ? In objective C , we use protocols now i want to do the same in cocos2dx but not able to find a way to implement the same .
Please help Thanks in advance!
Protocols are pure abstract classes in C++ (classes which contain only pure virtual methods):
class MyProtocol
{
public:
virtual void myProtocolMethod() = 0;
};
To implement protocol you inherit it and override its methods implementing them:
class MyClass : public MyProtocol
{
public:
virtual void myProtocolMethod()
{
// here you implement it
}
};
Thanks
It really helped me
Igor Zavorotkin wrote:
Protocols are pure abstract classes in C++ (classes which contain only pure virtual methods):
[…]
>
To implement protocol you inherit it and override its methods implementing them:
[…]
class MyClassDelegate
{
public:
virtual void myDelegateMethod() = 0;
};
class MyClass
{
public:
static void doSomething(int a, int b, MyDelegate *delegate)
{
m_delegate = delegate;
//doSomething........
this->m_delegate->myDelegateMethod();
}
private:
MyDelegate* m_delegate;
};
class MyUserClass : public MyClassDelegate
{
void calc()
{
MyClass::doSomething(1, 2, this);
}
void myDelegateMethod()
{
;
}
};
De Meng wrote:
[…]
Hi De Meng,
interesting post. But what kind of Object do you mean by “MyDelegate *delegate”? Would be very helpful if you could clarify this.
Thanks a lot!
Best regards
Should be a mistake in De Meng’s example. Not MyDelegate but MyClassDelegate.
I have added a detailed article here if interested
http://cobagames.com/2013/12/25/using-delegate-controls-in-cocos2d-x/
I also come from the Obj-C cocos2d world and use “protocols” heavily even with C++. I just define classes and call them protocols. Of course they are still classes. They don’t even need to be pure virtual with =0 etc, to make optional methods/functions just add a default implementation like {}. It might be some kind of overhead etc but I don’t think it’s a problem.
However I’ve ran into an issue recently where, for some reason I cannot understand yet, the delegates (or listeners, as I like to call them, when having several delegates for one main object) are being called even though I specifically already removed them as listeners. The delegates are the cocos2d-x scenes. I add them as listeners in init() and/or onEnterTransitionFinished() etc, then remove them as listeners in onExitTransitionDidStart() etc, but there seems to be some problem where the deallocated scenes/delegates are called even though they should already have been removed. Anyone have an idea off the top of their head what could be wrong? I thought the problem would be multithtreading etc, but I made sure to call everything on the main thread and I still get these problems. What could be wrong?