Came across this excellent article written by Matt Patenaude on memory management in cocoa and thought I should note down a part of it that clearly highlights our responsibilities when it comes to efficiently managing memory in our cocoa apps. Here they are:
- Every time you create an object with
alloc, you must release it, either immediately with
releaseor at a later time with
- Whenever you want to hold onto an object in an instance variable, you must claim ownership of it. If you created it yourself, you already own it; if not, you must copy or retain it.
- When your object is disposed of, you must relinquish ownership of any objects you have claimed in instance variables; this is done in your
- You should never attempt to release an object you don’t own — this includes objects obtained using convenience constructors.
- Never expect another object to release an object for you. If you need to wash your hands of an object before returning it, autorelease it.
- Every time you increase an object’s retain count, you must also decrease it.
Here are also some points I gathered from the article that I find it useful to help me understand cocoa memory management:
- Under GC (Garbage Collection) environment, ‘Reference Counting’ is used when autorelease is called upon an object
- Under Managed Memory environment, ‘Retain Counting’ is used where alloc, retain and copy would +1 to the retain count while release or an assignment of nil to an object via setters would -1 on the retain count