Today I faced with problem of updating objects in cocos2d-x framework. I try to download some text in asynchronous thread and then update text in CCTextFieldTTF and after that text field is disappear.
void HelloWorld::callbackFunc(void *Layer, std::vector<promowall::CItem> Items) {
cocos2d::CCLayer *layer = static_cast<cocos2d::CCLayer *>(Layer);
cocos2d::CCLabelTTF *label = dynamic_cast<cocos2d::CCLabelTTF *>(layer->getChildByTag(10));
label->setString("test");
}
I will be very appreciate if somebody will help me and explain how can I work with openGl and with pthreads.
If your callbackFunc is called from this asynchronous thread it may cause race conditions that might cause such a behaviour (cocos caches all the rendered font labels and the CCTextureManager is not thread safe).
Also (I think you can find the following info in Apple's OpenGL programming guide) - it is not safe to call all the OpenGL methods from different threads. And if you create this string "test" in a different thread, cocos actually ends up creating a new OpenGL texture (which might be not proper since created in a different thread). I think you can check this theory by creating a different label with the same "test" text somewhere else (on main thread) - if the one created in your code snippet no longer disappears - it means the theory is correct :)
How to fix it?
I believe you have to create the label (or set text on it) in your main UI thread - for example remember the result of your async callback in a queue and check it periodically in your update method somewhere. And remember about proper locking.