内存管理,防止内存泄露
如果a类引用某个那么内存块加1,如果a类不在引用了,内存块减一,当计数为0的时候,清空这个内存块。
retain()函数
void Ref::retain() { CCASSERT(_referenceCount > 0, "reference count should greater than 0"); ++_referenceCount; }
release()函数
void Ref::release() { CCASSERT(_referenceCount > 0, "reference count should greater than 0"); --_referenceCount; if (_referenceCount == 0) { #if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) auto poolManager = PoolManager::getInstance(); if (!poolManager->getCurrentPool()->isClearing() && poolManager->isObjectInPools(this)) { // Trigger an assert if the reference count is 0 but the Ref is still in autorelease pool. // This happens when ‘autorelease/release‘ were not used in pairs with ‘new/retain‘. // // Wrong usage (1): // // auto obj = Node::create(); // Ref = 1, but it‘s an autorelease Ref which means it was in the autorelease pool. // obj->autorelease(); // Wrong: If you wish to invoke autorelease several times, you should retain `obj` first. // // Wrong usage (2): // // auto obj = Node::create(); // obj->release(); // Wrong: obj is an autorelease Ref, it will be released when clearing current pool. // // Correct usage (1): // // auto obj = Node::create(); // |- new Node(); // `new` is the pair of the `autorelease` of next line // |- autorelease(); // The pair of `new Node`. // // obj->retain(); // obj->autorelease(); // This `autorelease` is the pair of `retain` of previous line. // // Correct usage (2): // // auto obj = Node::create(); // obj->retain(); // obj->release(); // This `release` is the pair of `retain` of previous line. CCASSERT(false, "The reference shouldn‘t be 0 because it is still in autorelease pool."); } #endif #if CC_REF_LEAK_DETECTION untrackRef(this); #endif delete this; } }
autorelease()相当于 自动的retain()和release()。采用了池的计数
object的定义
就是ref
还可以通过右键点击某个函数,计算层次结构和调用。
时间: 2024-10-06 14:51:29