How can identify strong reference cycles in Swift?

前端 未结 5 1888
无人及你
无人及你 2021-01-30 07:09

Is there a tool or method to locate strong references cycles in my SWIFT code?

A strong reference cycle is when two instances of classes reference each other without

5条回答
  •  有刺的猬
    2021-01-30 08:05

    The method for finding strong reference cycles is the same in Swift as it is in Objective-C.

    You'd run the app from Xcode, exercise the app sufficiently to manifest the cycle, and then tap on the "debug memory graph" button (). You can then select an unreleased object in the panel on the left and it will show you the memory graph, often which can clearly strong reference cycles:

    Sometimes the memory cycles are not as obvious as that, but you can at least see what object is keeping a strong reference to the object in question. If necessary, you can then track backwards and identify what's keeping a strong reference to that, and so on.

    Sometimes knowing what sort of object is keeping the strong reference is insufficient, and you really want to know where in your code that strong reference was established. The "malloc stack" option, as shown in https://stackoverflow.com/a/30993476/1271826, can be used to identify what the call stack was when this strong reference was established (often letting you identify the precise line of code where these strong references were established). For more information, see WWDC 2016 video Visual Debugging with Xcode.

    You can also use Instruments to identify leaked object. Just run the app through Instruments with the Allocations tool, repeatedly (not just once or twice) returning the app back to some steady state condition and if memory continues to go up, then you likely have a strong reference cycle. You can use the Allocations tool to identify what sort of objects are not being released, use "record reference count" feature to identify precisely where these strong references were established, etc.

    See WWDC 2013 video Fixing Memory Issues and WWDC 2012 video iOS App Performance: Memory for introductions to identifying and resolving memory issues. The basic techniques proposed there are still applicable today (though the UI of Instruments tools has changed a bit ... if you want introduction to the slightly changed UI, see WWDC 2014 video Improving Your App with Instruments).

    As an aside, "garbage collection" refers to a very different memory system and isn't applicable here.

提交回复
热议问题