Objective-C Memory Management, The Rules

Objective-C Ref “There are only 4 basic rules when it comes to memory management in Objective-C:

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.

That’s it. The first two are the most important and we’ll get into the basics of object ownership next.”

Just an FYI for those coming from another platform, or language. Remember, Objective-C’s parent is plain ole C, and you can mix C and C++ with your Objective-C. Keep the alloc/free, new/delete rules in mind when allocating objects. Also remember Objective-C objects are reference counted objects. If you want to keep an object around bump its retain count by doing…

anObject = [object retain];

When you’re done make sure you do

[object release];

Otherwise you’ll have a leak in your code.

I’d recommend a quick look at Cocoa Dev Central’s Learn Objective-C tutorial. It’s very good.

Once you have the rules figured out it’s fairly straight forward.