Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In swift, how to get memory back to normal after an SKScene is removed?

I created a simple game with SpriteKit, however every time I run the game, the memory usage in simulator increases about 30mb, but never decreases when the game is finished.

When I run the game over ten times the simulator gets slower and slower and eventually crashes.

In this simple game I have two controllers and a gamescene:

MainController calls GameViewController via a button triggered

In GameViewController, gamescene is initialised in this way:

class GameViewController: UIViewController
{

  var skView:SKView!

  var scene:GameScene!

  override func viewDidLoad() {

      super.viewDidLoad()
      scene = GameScene(size: view.bounds.size)
      skView = view as SKView
      skView.ignoresSiblingOrder = true
      scene.scaleMode = .ResizeFill

      scene.viewController = self
      skView.presentScene(scene)

  }

//with a prepareForSegue deinitialises the scene and skview:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "GameFinished"{

        scene.removeAllActions()
        scene.removeAllChildren()
        scene.removeFromParent()
        scene = nil

        skView.presentScene(nil)
        skView = nil

        let target = segue.destinationViewController as MainController
    }
  }
}

In the GameScene, viewController is a property

var viewController:GameViewController? = GameViewController()

the segue is triggered with this:

self.viewController!.performSegueWithIdentifier("GameFinished", sender: nil)

I've also tried putting remove methods into deinit in GameScene:

  deinit{
    self.removeAllActions()
    self.removeAllChildren()
  }

Still wouldn't work

like image 971
Fan Zhang Avatar asked Jun 17 '15 13:06

Fan Zhang


1 Answers

Your GameViewController has a strong reference to your GameScene. And your GameScene had a strong reference to your GameViewController. This leads to a strong reference cycle, which means that neither objects will be deallocated.

You need to declare your viewController property in your GameScene as weak.

weak var viewController:GameViewController? = GameViewController()
like image 115
Epic Byte Avatar answered Nov 15 '22 23:11

Epic Byte