问题描述
我用 SpriteKit 创建了一个简单的游戏,但是每次运行游戏时,模拟器中的内存使用量都会增加大约 30mb,但游戏结束后不会减少.
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 通过触发按钮调用 GameViewController
MainController calls GameViewController via a button triggered
在 GameViewController 中,游戏场景是这样初始化的:
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
}
}
}
在GameScene中,viewController是一个属性
In the GameScene, viewController is a property
var viewController:GameViewController? = GameViewController()
segue 是这样触发的:
the segue is triggered with this:
self.viewController!.performSegueWithIdentifier("GameFinished", sender: nil)
我也试过将 remove 方法放入 GameScene 中的 deinit 中:
I've also tried putting remove methods into deinit in GameScene:
deinit{
self.removeAllActions()
self.removeAllChildren()
}
还是不行
推荐答案
你的 GameViewController
对你的 GameScene
有一个强引用.您的 GameScene
对您的 GameViewController
有很强的引用.这会导致强引用循环,这意味着两个对象都不会被释放.
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.
您需要在 GameScene
中将 viewController 属性声明为 weak.
You need to declare your viewController property in your GameScene
as weak.
weak var viewController:GameViewController? = GameViewController()
这篇关于快速,删除 SKScene 后如何使内存恢复正常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!