兩個cache:CCTextureCache、CCSpriteFrameCache的使用

firedragonpzy發表於2012-07-31
[i][b]本文為firedragonpzy原創,轉載務必在明顯處註明:
轉載自【Softeware MyZone】原文連結: http://www.firedragonpzy.com.cn/index.php/archives/312[/b]
[/i]
注意cache的使用:
1、CCSpriteFrameCache使用:
CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
cache->addSpriteFramesWithFile("animations/grossini.plist");
在離開的時候:
void SpriteFrameTest::onExit()
{
SpriteTestDemo::onExit();
CCSpriteFrameCache *cache = CCSpriteFrameCache::sharedSpriteFrameCache();
cache->removeSpriteFramesFromFile("animations/grossini.plist");
或者:CCSpriteFrameCache::sharedSpriteFrameCache()->removeUnusedSpriteFrames();
}
大家先看看sharedSpriteFrameCache的原始碼:
CCSpriteFrameCache* CCSpriteFrameCache::sharedSpriteFrameCache(void)
{
if (! pSharedSpriteFrameCache)
{
pSharedSpriteFrameCache = new CCSpriteFrameCache();
pSharedSpriteFrameCache->init();
}

return pSharedSpriteFrameCache;
}
CCSpriteFrameCache::~CCSpriteFrameCache(void)
{
CC_SAFE_RELEASE(m_pSpriteFrames);
CC_SAFE_RELEASE(m_pSpriteFramesAliases);

}

並沒有autorelease,不會持有,當一釋放的時候就會被刪除

2、CCTextureCache使用:
SpriteNewTexture::SpriteNewTexture()
{
setIsTouchEnabled( true );

CCNode* node = CCNode::node();
addChild(node, 0, kTagSpriteBatchNode);

m_texture1 = CCTextureCache::sharedTextureCache()->addImage("Images/grossini_dance_atlas.png");
m_texture1->retain();
m_texture2 = CCTextureCache::sharedTextureCache()->addImage("Images/grossini_dance_atlas-mono.png");
m_texture2->retain();

m_usingTexture1 = true;

for(int i=0;i<30;i++)
addNewSprite();
}

SpriteNewTexture::~SpriteNewTexture()
{
m_texture1->release();
m_texture2->release();
}

大家先看看sharedTextureCache的原始碼:
CCTextureCache * CCTextureCache::sharedTextureCache()
{
if (!g_sharedTextureCache)
g_sharedTextureCache = new CCTextureCache();

return g_sharedTextureCache;
}


CCTextureCache::~CCTextureCache()
{
CCLOGINFO("cocos2d: deallocing CCTextureCache.");

CC_SAFE_RELEASE(m_pTextures);
}
也是沒有autorelease,不會持有,當一釋放的時候就會被刪除,若想持有,按照上述例子retain和release

相關文章