Interfacelab.com: “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.
One reply on “Objective-C Memory Management, The Rules”
[…] counting is a pain in the keister, until you understand the rules. ARC is going to become an important tool in the quest to creating error free code. If you’ve […]