Debugging leaked Core Data objects

Recently I came across a problem where the Leaks tool in Instruments was informing me that I was leaking an instance of NSManagedObjectContext.

"OK" I thought, "no problem; show me who's retained the context, but forgotten to release it, and I'll fix in a jiffy." Ah, but what's this? There's been a single increment of the retain count (when the object was first allocated), and nothing since then. "Lies," I said to myself. "Lies! For I can quite clearly see in the debugger that my document object gets deallocated, sending a -release message to the context".

Clearly, something else is coming into play here. After some hunting, as far as I can tell:

Both NSManagedObject and NSManagedObjectContext implement their own reference counting.

It seems that by doing so, Instruments is unable to track -retain or -release calls. So it can tell you that an instance has been leaked, but no more. Bummer.

Fortunately, this custom implementation means you can track the problem yourself moderately easily.

  • Set breakpoints on -[NSManagedObjectContext retain] and -[NSManagedObjectContext release] (or on NSManagedObject if that's your problem)
  • Step through in the debugger looking for a -retain not balanced by a -release.
© Mike Abdullah 2007-2015