How do I find a reference cycle using the memory graph debugger?

Generated on 8/2/2024

1 search

To find a reference cycle using the memory graph debugger, you can follow these steps:

  1. Open the Memory Graph Debugger: Start by running your app and then open the memory graph debugger in Xcode.

  2. Filter Leaked Allocations: Use the "Show only leaked allocations" button in the filter bar to focus on potential leaks. This button has a triangular icon.

  3. Identify Leaks: Look for types that are leaking. For example, you might see leaks of specific classes like thumbnail loader and thumbnail renderer.

  4. Inspect References: Select one of the leaked objects to inspect its references. The memory graph debugger will show you the reference relationships. For instance, you might see a small reference cycle between a thumbnail renderer, a thumbnail loader, and a closure context.

  5. Analyze Closure Contexts: Closures in Swift capture references strongly by default, which can create reference cycles. The memory graph debugger labels these allocations as closure contexts. Each closure context corresponds to a live closure.

  6. Break the Cycle: To break the reference cycle, you need to find the code that created the closure. The memory graph debugger can help you navigate to the source code responsible for the allocation. You might need to change the ownership qualifier from strong to weak or unowned to break the cycle.

For a detailed walkthrough, you can refer to the session Analyze heap memory starting at 21:43. This section discusses identifying and resolving reference cycles involving Swift closure contexts.