Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

swift - Knowing where retain cycles are and removing them

I was wondering if there was an easy way (or at least a way) to find out where retain cycles exist in your program. Also, if I then know where these retain cycles exist, depending on their types (e.g. variable or closure), how do I make them weak. I need to stop all retain cycles with self (my GameScene) so that it deallocates when I don't need it anymore and I want to restart it.

Any tips, advice, answers, and feedback would be greatly appreciated (and providing specific code and examples would be preferred). Thank you.

Edit: @Sweeper's answer was just what I was looking for. If you're having the same issue his answer will help. Thanks @Sweeper!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are using Xcode 8 or above, you can use the memory graph thingy to see what object holds a reference to what object.

To see the memory graph, first build and run your app with Xcode. When you want to check whether all the instances you created are discarded properly, go to this tab on the left pane:

enter image description here

Then press the button on the right there:

enter image description here

After that, select the bottom-most option - View Memory Graph Hierarchy:

enter image description here

Now it will show you all the objects that are in memory:

enter image description here

In my case, I have a GameSystem object, 6 ButtonNode objects and a few others. You'll notice that there is a little ! beside the GameSystem object. That means this object is leaked. Also, GameScene should not be in memory anymore because the current scene is TitleScene. Let's see what is retaining it by clicking on the instance:

enter image description here

Now you can clearly see that it is retained by a closure!

That is how you use the memory graph to see where you should put weak-references and avoid retain cycles.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...