且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

呈现 SpriteKit 场景时出现内存泄漏

更新时间:2022-05-28 20:58:02

首先你正确地展示了 SKScene,你是正确的,你应该能够相信旧场景会被清理干净.我的意思是你不需要做任何其他事情来让它发布.

First off you are presenting SKScene's correctly and you are correct you should be able to trust that the old scene will get cleaned up. By that I mean there is nothing else you need to do to make it release.

话虽如此,您可能已经做了一些事情来创建循环引用.希望其中几项检查可以帮助您找到它.

Now with that being said there are things that you may have done to create a circular reference. Hopefully a couple of these checks will help you track it down.

我总是首先看你的播放器.如果您的场景具有播放器属性并且您的播放器具有场景属性,这可能会阻止场景释放.玩家抓住场景,场景抓住玩家.我怀疑这是你的情况,但值得检查.

The first place I always look is at your player. If your scene has a player property and your player has a scene property this could prevent the scene from deallocating. Player holds on to the scene and scene holds on to player. I doubt this is your case but worth checking.

第二个看点是否还有其他与该场景有参考或属性的东西?一个常见的问题是当您创建自己的委托方法时.如果你的玩家做了一个动作,然后调用一个方法回到那个场景.玩家应该只对那个场景有弱引用.我自己做过这个,并且看到其他人在创建自定义委托或协议并保持对它的强引用而不是弱引用时这样做.

Second place to look is there anything else that has a reference or property to that scene? A common issue is when you create your own delegate method. If your player does an action and then calls a method back to that scene. The player should only have weak references to that scene. I have done this myself and seen other do it where they create a custom delegate or protocol and keep a strong reference to it instead of weak.

第三个查看位置是代码中您调用 self 的任何位置.这在 SKAction 的运行块中很常见.您可能有一个在场景中调用方法的动作,并且您可能在该 SKAction 的那个场景上有一个属性.由于运行块,动作具有对场景的引用,并且场景具有对动作的引用.因此,查找 self 并查看该对象是否是该场景中的属性.

Third place to look is anywhere in your code where you call self. This is common in run blocks of SKActions. You may have an action that calls a method on the scene and you may have a property on that scene of that SKAction. The action has reference to the scene due to the run block and the scene has a reference to the action. So look for self and see if that object is a property on that scene.

希望这可以帮助您找到它.我知道跟踪这样的泄漏可能会令人沮丧,而这些都是我过去看到的常见问题.

Hopefully that helps you track it down. I know it can be frustrating tracking a leak like this down and those are common issues I have seen in the past.