Memory management in Objective-C can sometimes be confusing, specially if you are used to writing code in languages that support automatic garbage collection. Here are 3 simple rules that you should follow in your code:
- If you allocated, copied, or retained an object, then you are responsible for releasing the object with either -release or -autorelease when you no longer need the object. If you did not allocate, copy, or retain an object, then you should not release it.
- When you receive an object (as the result of a method call), it will normally remain valid until the end of your method and the object can be safely returned as a result of your method. If you need the object to live longer than this–for example, if you plan to store it in an instance variable–then you must either -retain or -copy the object.
- Use -autorelease rather than -release when you want to return an object, but also wish to relinquish ownership of the same. Use -release where ever you can, for performance reasons.
If you are not very familiar with memory management or feel like you want to read more about it, check out the complete article where I got the 3 rules above from: http://bit.ly/jZyPcg