Search code examples
arraysiteratorcocos2d-xenumerator

CCArray enumerator object


As far as I know it doesn't exist.

    CCArray *array = CCArray::create();
    CCArrayEnumerator *enumerator = array->createEnumerator();
    ...

    CCObject *nextObjectOrNull = enumerator->nextObject();
    CCObject *currentObjectOrNull = enumerator->peekCurrentObject();

This class would make my code simpler, and if no one coded it, I will do it no time. But I haven't found any requests or forum posts about the need for this class. Which is strange.


Solution

  • I wrote a simple class, which does the job. Suggestions are welcome.

    CCArrayEnumerator.h:

    #include "cocos2d.h"
    
    class CCArrayEnumerator : public cocos2d::CCObject{
    
    public:
        static CCArrayEnumerator* create(cocos2d::CCArray* array);
        cocos2d::CCObject* nextObject();
        cocos2d::CCObject* peekCurrentObject();
    private:
        cocos2d::CCArray* _array;
        CCArrayEnumerator();
        ~CCArrayEnumerator();
        virtual bool init(cocos2d::CCArray* array);
    
        int _currentIndex;
    };
    

    CCArrayEnumerator.cpp:

    #include "CCArrayEnumerator.h"
    USING_NS_CC;
    
    CCArrayEnumerator* CCArrayEnumerator::create(cocos2d::CCArray* array){
        CCArrayEnumerator *pRet = new CCArrayEnumerator();
        if (pRet && pRet->init(array))
        {
            pRet->autorelease();
            return pRet;
        }
        else
        {
            CC_SAFE_DELETE(pRet);
            return NULL;
        }
    }
    
        cocos2d::CCObject* CCArrayEnumerator::nextObject(){
        CCObject *retval = NULL;
    
        if(_array->count() > _currentIndex + 1){
            _currentIndex++;
            retval = _array->objectAtIndex(_currentIndex);
        }
    
        return retval;
    }
    
    cocos2d::CCObject* CCArrayEnumerator::peekCurrentObject(){
        CCObject *retval = NULL;
    
        if(_currentIndex != -1 && _array->count() > _currentIndex){
            retval = _array->objectAtIndex(_currentIndex);
        }
    
        return retval;
    }
    
    CCArrayEnumerator::CCArrayEnumerator():
     _array(NULL)
    ,_currentIndex(-1){
    
    }
    
    CCArrayEnumerator::~CCArrayEnumerator(){
        if(_array){
            _array->release();
            _array = NULL;
        }
    }
    
    bool CCArrayEnumerator::init(cocos2d::CCArray* array){
    
        // Superclass CCObject has no init.
    
        CCAssert(_array == NULL,"CCArrayEnumerator is already initialized.");
    
        _array = array;
        _array->retain();
    
        return true;
    }