Secret Memory Management Tip: Get the Retain Count!

Matthew Campbell, April 1st

Has this happened to you: an app was running along just fine and suddenly it disappears into the iPhone simulator ether?

If it has, then you probably need this memory management tip because it sounds like you are over releasing your objects. As you probably know by now, the iPhone keeps track of how much memory to use by something called “reference counting”.

If an object’s reference count is zero, it goes away and frees up its memory. Otherwise, the object sticks around.

When an app suddenly disappears from the simulator it usually means that the retain count (another name for reference count) has gone to zero, the system cleared it away but you tried to access it! When you attempt to send a message to a random bit of memory that used to be your object then – puff – you whole app just disappears.

How do you control the retain count? Whenever you use alloc to create an object and when you send a retain message to an object you increase the retain count by one. When you release an object you decrease the retain count by one.

It sounds simple, but it can be tricky when you retain or release too much. What would be nice is if you could find out what the retain count was at any given time.

Actually, you can!

It is actually pretty simple – every object has a “retainCount” function that returns an unsigned integer that you can print to the log. All you need to do is stick that in places where you are unclear about the status of your retain count.


Here is what the output to the log would be:


Some classes do not work well with this – if you see something with a retainCount in the millions range then be a bit skeptical of that. NSString is one of these classes – try this example with NSString and you will see what I mean.

Using memory is one of the biggest challenges you face with the iPhone. What are some tricks and tips that you use when debugging memory problems?