Cocos2d-x projects sometimes encounter the need to register callback functions, and then trigger in the appropriate conditions, some broadcast messages similar to android. The main problem encountered in the project is network data processing. Below are the main implementation ideas, hoping to help.
Define the message callback class MessagePushEntry, which follows the data structure and specification of cocos2d-x as much as possible, mainly has the callback object, the callback method and the linked list data structure used to traverse.
Class MessagePushEntry {
Private:
MessagePushEntry (const char * key, CCObject * target, SEL_MsgCallFuncO selector );
Public:
~ MessagePushEntry ();
Private:
# Deprecision MAX_KEY 256
Char msgKey [MAX_KEY];
CCObject * target;
SEL_MsgCallFuncO selector;
Public:
UT_hash_handle hh;
};
SEL_MsgCallFuncO is a custom callback macro that accepts callback data. msgKey is the registration filter condition.
Typedef void (CCObject: * SEL_MsgCallFuncO) (void *);
# Define msgcallfuncO_selector (_ SELECTOR) (SEL_MsgCallFuncO) (& _ SELECTOR)
Below is the registration callback
AddMessageCallBack (const string key, CCObject * target, SEL_MsgCallFuncO selector ){
If (target = NULL)
Return;
MessagePushEntry * pElement = NULL;
HASH_FIND_STR (m_messagePush, key. c_str (), pElement );
If (pElement = NULL ){
Target-> retain ();
PElement = new MessagePushEntry (key. c_str (), target, selector );
HASH_ADD_STR (m_messagePush, msgKey, pElement );
}
Return;
}
Because of the Project relationship, the project-related code is saved here, but the problem should not be big, the main implementation is fully in accordance with the cocos2d-x writing standards, if you have an understanding of the engine, it should be understandable.
The above is the general implementation of registration callback, and then the callback is triggered as appropriate.
CheckPopMsg (float dt ){
MessagePushEntry * pElement = NULL;
HASH_FIND_STR (m_messagePush, onlyKey. c_str (), pElement );
If (NULL = pElement ){
CCLOG ("Message warn: no seletor ");
Return;
}
CCObject * myTarget = pElement-> target;
SEL_MsgCallFuncO mySeletor = pElement-> selector;
If (myTarget & mySeletor ){
(MyTarget-> * mySeletor) (msg );
}
HASH_DEL (m_messagePush, pElement );
PElement-> target-> release ();
CC_SAFE_DELETE (pElement );
}
OnlyKey is the filter condition of the message mentioned above, which is consistent with the key at registration.
Msg is the data that we need to call back. Here, the landlord uploads the message data class and waits for processing the callback function.
Note that the landlord did not perform a specific test, but the problem should exist. After the callback is registered, the target will be retain () once, therefore, if a callback is registered and not triggered, memory overflow may occur. Therefore, you do not need to delete the registration in the onExit () method of target when the callback exits directly!