TIP - debugging bugs with release / retain

Hey,
I found this method very useful for debugging problems with releasing and retaining…

I found that as my system got a lot more complex, lot of different things would retain my objects and I lost track of when and why.
Obviously is it MUCH better to really carefully keep track of what is happening, but this is a tip for people that have lost track or havent really understood the concept yet…

I found myself in these situations a fair bit…
sometimes you get a bad access when you try and access an object - its been released, but when?
sometimes you get a problem when you release an object - because its already been deleted… maybe you forgot to retain it… but when?
sometimes a object doesnt get deleted… it takes up memory in the background and maybe even accidentally responds to new notifications. - why didnt it get released? is it getting retained once too often?

I wanted to put a breakpoint in the retain() and release() function or something like my PhysicsBall object…
obviously the function is only on CCObject, so you cant pause at a breakpoint to see exactly when that very object is being retained or released in order to debug.

modify CCObject.h like this:

#ifdef DEBUG_RETAIN
virtual void release(void);
#else
void release(void);
#endif

#ifdef DEBUG_RETAIN
virtual void retain(void);
#else
void retain(void);
#endif

instead of the normal

void release(void);
void retain(void);

then in your object that inherits from ccobject, (like PhysicsBall) add to the header:
#ifdef DEBUG_RETAIN
virtual void retain() {CCObject::retain(); };
virtual void release() {CCObject::release(); };
#endif

if you add:
#define DEBUG_RETAIN 1
to prefix.pch then these changes will be in effect and you can put breakpoints on the lines in your object and see in the tree what functions are correctly / incorrectly releasing an retaining.
(disable it by removing the ‘define’ line if you want it to stop… else it will significantly slow everything down.)

still got tot do a lot of the work yourself in the debugger - but thats a much better skill to learn than asking on forums… teach a man to fish.
hope that helps?