【问题标题】:CCArray enumerator objectCCArray 枚举器对象
【发布时间】:2014-01-23 13:13:42
【问题描述】:

据我所知不存在。

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

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

这个类将使我的代码更简单,如果没有人编写它,我将立即编写。但是我没有找到任何关于需要这个类的请求或论坛帖子。这很奇怪。

【问题讨论】:

  • ...你的问题是?

标签: arrays iterator cocos2d-x enumerator


【解决方案1】:

您可以编写自己的代码,但已经有一个可以用于相同的宏。

这是伪代码:

CCArray *array = this->getChildren();  

CCObject* currentObject = NULL;  
CCARRAY_FOREACH(array , currentObject )  
{  
    CCNode *node = (CCNode*)currentObject;
}

【讨论】:

    【解决方案2】:

    我写了一个简单的类来完成这项工作。欢迎提出建议。

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      相关资源
      最近更新 更多