Search code examples
iosobjective-csprite-kitdeallocskscene

How to deallocate unused SKScene


I have a SKScene object setup in GameViewController. I implemented dealloc into the SKScene subclass as follow:

- (void)dealloc {
    NSLog(@"Dealloc: %@", self);
}

Now I want to present another view controller on top of GameViewController. I used storyboard segue to do this. But after the new view controller is presented, I never received the SKScene dealloc. It got stuck in the memory. My app starts to freeze after a few minute due to low memory. How can I dealloc the scene after presenting the new view controller.


Solution

  • In order to deallocate you SKScene instance -> you Should Eliminate every pointer that retains it -> then ARC will automagically release it.

    Simply call the [skView presentScene:nil]; method which also will remove the SCScene and deallocate it by setting SKView.scene property to nil.

    SKView *skView = (SKView *)self.view; 
    GameScene *scene = (GameScene *)skView.scene; 
    
    for(SKNode * child in scene.children)
    {
        [child removeAllActions];
    }
    [scene removeAllChildren];
    [scene removeAllActions];
    [skView presentScene:nil]; 
    

    Note Normally you don't have to remove everything from the SKScene if your memory is managed right just call [skView presentScene:nil]; method and ARC will take care of it.

    Apparently you had something inside the SKScene that retained it. So by removing everything from it, we eliminated the retain cycle.

    This solution will not always work, it will work only if one of the SKActions or SKNodes are retaining the SKScene which were the issue in your case, However your SKScene could be retained from somewhere else and this answer wouldn't really help you