1

Shame on me for this, but yes. I am having problems with this even if I am using ARC.

My main question is: am I having a circular reference in my code?

My code description:

I have a game scene with a series of child nodes (background, playerEntity, inputlayer). The issue is that when I trigger game over and replace the scene the scene would not deallocate (I added a dealloc method in the game scene even if not needed as I am using ARC).

I believe that this is due to the fact that in the child nodes I refer to the game scene and in the game scene I refer to them, creating a circular reference.

E.g. In the game scene update method I call the following:

-(void) update:(ccTime)delta
{
bool isGamePaused = [GameController sharedGameController].isGamePaused;

if(isGameOverInProgress==true){
    //Do whatever game over animation u like
}
else if(isGamePaused==false)
{
    elapsedTime+=delta;

    //Update input layer
    InputLayerButtons *inputLayer = (InputLayerButtons *) [self getChildByTag:InputLayerTag];
    [inputLayer update:delta];

    //Move background
    ParallaxMultipleBackgroundOneBatchNode* background = (ParallaxMultipleBackgroundOneBatchNode*) [self getChildByTag:BackgroundNodeTag];
    [background update:delta];

    //verify enemies bullet collision
    [self verifyPlayerBulletCollision];
    [levelSprites update:delta];

    //Update bullets position
    [bulletCache updateVisibleBullets:delta];

I know that is a kind of crazy approach but I wanted to avoid scheduling updates in the child nodes in order to have full control in the ShooterScene class of what was happening in the game. I don't use a semi-singleton patter for the ShooterScene class and instead, I have a semi-singleton GameController class instance that I use to communicate the game state between nodes.

But in some child nodes I had to refer to the parent ShooterScene because for example using the semisingleton GameController class to store the ship position turned out in a too slow response (e.g. reading the position in the update method and updating the ship accordingly proved much slower than updating it directly as I do in here). Hence my approach is not 100% clean as I wanted it to be (I wanted to avoid all references to parent classes to avoid the issue of circular references and also to keep control of all events in the ShooterScene class).

So, as example, here is how I update the ship position from the input layer (namely InputLayerButtons):

-(void) update:(ccTime)delta
{
    // Moving the ship with the thumbstick.
    ShooterScene * shooterScene = (ShooterScene *) [self parent];
    ShipEntity *ship = [shooterScene playerShip];
    delta = delta * 2.0f;

    CGPoint velocity = ccpMult(joystick.velocity, 200);
    if (velocity.x != 0 && velocity.y != 0)
    {
        ship.position = CGPointMake(ship.position.x + velocity.x * delta, ship.position.y + velocity.y * delta);
    }     
}

I thought that it was ok to refer to the parent scene and that this would not cause a circular reference. But it seem to happen, so I am confused on this.

Here is the code of the game over method, the dealloc method of ShooterScene is never called (cleanup instead is called):

   [[CCDirector sharedDirector] replaceScene:[CCTransitionFade transitionWithDuration:4.0 scene:[MainMenuScene scene] withColor:ccc3(255, 255, 255)]];

Is there something in replaceScene that I don't understand? I couldn't find the code for replaceObjectAtIndex so here I post only the Cocos2d 2.0 code for replaceScene

-(void) replaceScene: (CCScene*) scene
{
    NSAssert( scene != nil, @"Argument must be non-nil");

    NSUInteger index = [scenesStack_ count];

    sendCleanupToScene_ = YES;
    [scenesStack_ replaceObjectAtIndex:index-1 withObject:scene];
    nextScene_ = scene; // nextScene_ is a weak ref
}

I tried to see if the dealloc method would be called in other scenes (simpler that ShooterScene and with no potential circular references) and it did worked. So I am pretty confident that it is due to circular references but how can I detect the piece of code that makes this happen?

mm24
  • 9,280
  • 12
  • 75
  • 170

1 Answers1

2

ARC does not prevent retain cycles. Using zeroing weak references however greatly decreases the chances of creating a retain cycle.

As a general rule of thumb regarding cocos2d node hierarchy & retain cycles:

You do not have a retain cycles if you:

  • keep a strong reference to a child (or grandchild) node

Yes, that's the only rule that's safe in terms of retain cycles in cocos2d! That means that references to nodes which are not children or grandchildren of the node should never be strong (retaining) references.

You are guaranteed to have a retain cycle if you:

  • keep a strong reference to a parent (or grandparent) node
  • keep a strong reference to a sibling node, and the sibling node keeps a strong reference to the original node either directly or indirectly

You may have a retain cycle if you:

  • keep a strong reference to a node that's not a child (or grandchild) node, depending on whether that node holds a strong reference back to the original node or other factors.

In your case that means by keeping a strong reference to the parent you created a retain cycle. Under ARC every ivar is a strong reference by default. You can do two things to resolve this and any other potential retain cycle:

  • change the property to be weak or the ivar to be __weak (requires iOS 5.0 as minimum deployment target - highly recommended)
  • set the ivar to nil in the node's -(void) cleanup method

How to create weak references:

// weak references to parent nodes are safe:
@interface MyClass : CCNode
{
    __weak CCLayer* _gameLayer;
}
@property (nonatomic, weak) CCScene* gameScene;
@end

How to cleanup properly:

-(void) cleanup
{
    _strongRefToNonChildNode = nil;
    [super cleanup];
}

-(void) momCallsShesAlmostHere
{
    [self cleanupApartment];  // just kidding :)
}

Cleaning up in dealloc as one might think would be appropriate is too late for resolving retain cycles. Because if you have a retain cycle, you obviously can't resolve it in dealloc since the retain cycle prevents the objects from deallocating in the first place.

Community
  • 1
  • 1
CodeSmile
  • 64,284
  • 20
  • 132
  • 217
  • Thnks!I actually realized that in my case I was not calling [super cleanup] in the ShooterScene cleanup method. So because I was not having any property/variable as reference to the parent scene in the child nodes the set to nil was not necessary (I was getting the parent scene in methods using self.parent and hence I think that after the method call this reference became automatically nil - see update in InputLayerButtons class). But thanks for your answer, is useful to have a proper understanding of this and without seeing your call to super dealloc I wouldn't have fixed it :) – mm24 Oct 16 '12 at 15:28