Search code examples
iphonexcodeiosmemory-leaksinstruments

Xcode, Instruments: How to find an ever-increasingly leaking object?


Hard to explain what I need in the subject line. If you have a better idea, feel free to edit it.

The problem is as follows:

An iOS app handles documents, always one at a time. Every time it closes a doc and opens a new, even if it's the very same doc, memory usage increases constantly, and always by the same amount.

So there's a leak. The code doesn't free (release) something. Maybe it's an array that adds a reference to an item of the doc, and which never gets cleared, although it should.

Of course, the Leaks Instrument won't help here, since it's all "proper" (it only finds allocations without an owner).

How do I use Instruments (or dtrace) to find this bugger now? It would help if I could simply identify one of those ever-added objects in Instruments, the rest will be easy.

So far, I've been using the Allocations instrument, setting the inspection range to the time when the old doc gets closed and the new one gets opened. Still, this shows thousands of objects, and only one of them is the one that is left over from the previous doc and is still alive although it shouldn't. That one object I need to identify.

I imagine that what I need is a feature in the Allocations tool that subtracts all allocations just added and also subtracts all allocations that existed after startup - what would remain are items created by a new doc but not released since then. Is there some way to get the sets of collected objects, group them into sets and do set operations like this? Probably not.

With about 20000 objects created every time the doc gets opened, and with about 50 source files involved, it's just not doable by looking at the source code nor by checking all the objects by hand.

Oh, and the static analyser doesn't help, either.


Solution

  • I think I figured it out:

    The secret lies in the correct use of the Mark Heap button:

    So far I only tried it once before and once after the loading of a new doc.

    But when I to this three times (load, Heapshot, load, Heapshot, load, Heapshot), then the middle Heapshot will list the objects that are still alive from just between the two doc loads around it, which is exactly what I was looking for.