I've seen lots of people asking questions about how to manage memory properly in Objective-C so I thought I'd list out some of the rules I follow when developing for the iPhone.
Objective-C is interesting because it introduces a few additional gotchas when compared to traditional C. In C, you write free() when you write malloc() and that's pretty much it. In Objective-C it's easy to forget things. So here are the rules I try to follow:
When adding a new member variable to a class, add a call to
releasein yourdeallocmethod as your immediate next action.When assigning to a member variable outside of
init*orloadViewetc.releaseit first. If you are assigning in a setter method, check the new value for equality first.When
releaseing a member variable outside ofdealloc, immediately assign a new value, ornil.When you type
allocfor a local variable, immediately add the appropriate release or autorelease code. Prefer autorelease.Move your
deallocmethod to immediately below your@synthesizelines. This reminds you to check your release calls and you can easily see any missing ones.If you implement your own
NSAutoReleasePoolblock, wrap it in a@try...@finally:NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; @try { // do stuff here } @finally { [pool release]; }If you implement a delegate property, don't retain the delegate. See this excellent post on how to avoid retain cycles (circular references): Rules to avoid retain cycles.
![Email me [email address]](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgJ_JhGL8XPx4ja4vtcBNqkgtWhsuFo6Hkr6_TBo3bTjfbu6yskRgIRz57JZ7zU2K7MNDuSfkugZq4CGkDuv5ZPKqYNwT3TlxU7jVXuxut-hxo58QzMeHipfm9tuz1S0HOlLYMVjbi9rpA/s400/email.png)