Memory management with Objective-C

The most daunting thing about learning Objective-C after living in the world of high level scripting languages is the memory management. From the beginning, I figured it would be a hassle, but I didn’t think it would be complicated. Turns out, it’s not even though there’s a lot written out there on the Web that makes it sound that way. The best article I’ve found is here: Objective-C Memory Management for Lazy People. Some simple rules make the whole project very easy.

  • If you own it, release it.
  • If you don’t own it, don’t release it.
  • Override dealloc in your classes to release the fields that you own.
  • Never call dealloc directly.

Which are made simpler by these rules about when you own something.

  • You own it if you alloc it.
  • You own it if you copy it.
  • You own it if you new it.

Easy. As soon as you write one of those three commands, ask yourself where you’re releasing the object in question. If you allocate something in your init method, you probably want to release it in your dealloc method. If you allocate it in a method and never use it again, you probably want to release it in the method. If you allocate it in one place and then need to pass it off somewhere else, you probably want to autorelease it, which is just like releasing except that it doesn’t happen right away. Autoreleasing is good for methods that return objects. Chances are that when your method returns an object, the object that called said method will have a way to retain the object on its own without your help. And if it doesn’t, it should. A lot of your convenience methods like NSArray’s arrayWithArray: provide you with autoreleased objects, which is nice. That’s why you don’t have to release them yourself.

Things get a bit more complicated when you throw properties into the mix, but I’ll leave that for another time.

Tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>