You Have to Learn the Magic

by Rob Bajorek on May 8, 2009

Bad things can happen when you don’t understand what you’re doing.

When writing my first iPhone application in Objective-C, I banged my head against the wall of memory management. EXC_BAD_ACCESS became a frequent and unwelcome guest during testing.

I have a C/C++ background, so picking up Objective-C was not particularly difficult. However, Objective-C objects are a different beast than I was used to. I soon noticed a theme while debugging my app; crashes happened around the words release and dealloc a lot.

I started sprinkling retains throughout my code, hoping to ward off the memory errors. Sometimes it worked, sometimes I created a leak, and sometimes the crash jumped somewhere else. It was like playing whack-a-mole. Bash a bug in one place, and it popped up in another.

The problem was, to me, Objective-C memory management was something magical. I created and deleted objects all the time, and usually it worked. But, I didn’t know the rules for when to retain. I was trusting the object fairies to know what I wanted to keep and what to whisk away.

Eventually, I stopped and said “There is something fundamental that I’m missing.” I spent an hour reading Apple’s Memory Management Programming Guide for Cocoa. It was like flipping on a switch in my head. I went back to my code, ripped out the useless retains, then picked off the bugs one by one.

Magical thinking is a recipe for disaster. You need to understand the tools you use. If something is a black box to you, take a crowbar and rip it open.

Don’t trust the fairies. They don’t take the support calls from your frustrated customers.  Learn the magic yourself.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Reddit
  • Slashdot
  • StumbleUpon

Leave a Comment

Powered by WP Hashcash

Previous post:

Next post: