An article on the Fun with Objective-C Tumblr today talks about learning Objective-C.
This is something any experienced Cocoa developer has been asked at least half a dozen times:
“What’s the best way to learn Objective-C/Cocoa?”
I have two answers to this question:
- Be curious
- Don’t be satisfied
There’s plenty to read in the full article, but it finishes with the following epithet:
- Know what a pointer is.
- Memorize the memory management rules.
- Never invoke
The second item there is one I’m frequently told is ‘really difficult’ to understand. It’s not. It’s really not. It looks like this:
- Only the owner of an object needs to even think about its memory management.
- You only own an object if you get it from a method whose name begins with any one of:
(er, no, it doesn’t. I’m being stupid. Sorry.)
- You also ‘own’ an object (technically, you own a single reference) if you send it the
- If the object doesn’t come from a method matching those rules, you don’t own it.
It’s that simple. If you call a method beginning with
copy, then you must use
-autorelease) to balance that call. If you don’t call one of those methods, you Needn’t Care.
How about CoreFoundation? That’s even simpler: you own an object if it comes from a method containing
Create. The same thing could be said about
Copy, but CoreFoundation’s copy constructors
are always careful to frequently already contain
Create, so we don’t need to. Anything named using
Get returns an already-managed reference, so you don’t need a
CFRelease for it.
See? Easy. A list of four keywords in Objective-C code indicate the only times you need to ever think about memory management. And one keyword in CoreFoundation to tell you the same.
Now, there are exceptions– usually when something missed the boat, or when an existing API needed to be changed to fix an internal memory-management issue. The documentation will tell you about these very rare cases, but the best way to catch them for now is judicious use of Build & Analyze. The Clang compiler’s static analysis tool knows all about these rules, and can be told about any differences to them by any API. It will tell you explicitly if you’ve released something you don’t own, or have failed to release something you do own. Use it. Love it.
Memory management in Cocoa isn’t difficult. There are rules, but they’re simple and easy to remember. The main thing to remember is:
Don’t over-think it.