Initialisation of a variable only once.

Initialisation of a variable only once.
0.0 0


Hello Guys,
I am working on one game in cocos2d-x (iOS). There I have created few scenes and did transitions in between those scenes. During each transition init() of each scene(layer) is called (Also constructor is called each time before init()). Now my question is, How can I make ONLY ONE time initialisation of my variable inside this init() or constructor, even when init() is called each time? Or any OTHER alternative solution for the same?

   CCUserDefault::sharedUserDefault()->setBoolForKey("firstTimeInit", false);

        bool firstTimeInit = CCUserDefault::sharedUserDefault()->getBoolForKey("firstTimeInit");

        if (!firstTimeInit)

         for(int i = 0; i < 10; i++)
           char szName[22] = {0};
           sprintf(szName, "Rank%i", i);


           int score = CCUserDefault::sharedUserDefault()->getIntegerForKey(szName);
           CCUserDefault::sharedUserDefault()->setBoolForKey("firstTimeInit", true);

I wrote this code inside init() method… and I want that firstTimeInit which I made false, initialise only once.


change this macro

#define RUN_ONCE(function)  \
    {                           \
        static bool __once__ = true;\
        if(__once__)            \
        {                       \
            function();          \
            __once__ = false;   \
        }                       \


Or use this snippet , which is based on C++11 lambda’s instead of rather ugly/error prone macro :slight_smile:


Thank you guys Will try it soon and let you know! :slight_smile: