我用SpriteKit创建了一个简单的游戏,但每次运行游戏时,模拟器中的内存使用量增加约30mb,但游戏结束后永远不会减少.
当我运行游戏超过十次时,模拟器变得越来越慢并最终崩溃.
在这个简单的游戏中我有两个控制器和一个gamecene:
MainController通过触发按钮调用GameViewController
在GameViewController中,gamescene以这种方式初始化:
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 } } }
在GameScene中,viewController是一个属性
var viewController:GameViewController? = GameViewController()
segue被触发:
self.viewController!.performSegueWithIdentifier("GameFinished",sender: nil)
我也试过在GameScene中将remove方法放入deinit:
deinit{ self.removeAllActions() self.removeAllChildren() }
仍然行不通
您的GameViewController强烈引用您的GameScene.而你的GameScene对你的GameViewController有很强的参考价值.这导致强大的参考周期,这意味着两个对象都不会被释放.
原文链接:https://www.f2er.com/swift/319995.html您需要将GameScene中的viewController属性声明为弱.
weak var viewController:GameViewController? = GameViewController()