Cocoaphony

Mac and iPhone, on the brain

Three Magic Words

Here are the three magic words: +alloc, -copy and +new. If you commit these magic words to memory, and devote yourself to a life of accessors, then Cocoa memory management should cause you no fear.

For those interested in the path to memory management enlightenment, you should first deeply understand every word of the Memory Management Rules. Don’t be afraid, it is very short, and if you will commit it to heart, you will avoid much suffering in the future.

Cocoa memory management is very simple and very consistent:

You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retainmessage. You are responsible for relinquishing ownership of objects you own using release orautorelease. Any other time you receive an object, you must not release it.

That’s the entirety of non-garbage-collected Cocoa memory management, the rest is, as they say, just commentary. If I were to add one more rule that will save you much heartache, it is this:

Retain things you care about for longer than this event loop. Release things when you stop caring about them.

Much trouble occurs in Cocoa programs when programmers violate this rule. When they think “I know such-and-such is retaining it for me, so I don’t need to retain it,” crashes follow. There is even some Apple sample code that does this (the NSURLConnection examples in particular), and I think it’s a mistake.