Avoiding the warnings
When you create an object - a window or button for example - memory is allocated to hold that object's data. The more objects you create, the more memory you use and the less there is available for additional objects you might need. Obviously, it's important to make available (that is, de-allocate) the memory that an object was using when the object is no longer needed. This task is called memory management.
Objective-C uses reference counting to figure out when to release the memory allocated to an object. It's your responsibility as a programmer to keep the memory-management system informed when an object is no longer needed.
Remember Reference counting is a pretty simple concept. When you create the object, it's given a reference count of 1. As other objects use this object, they use methods to increase the reference count and to decrease it when they're done. When the reference count reaches 0, the object is no longer needed, and the memory is de-allocated.
Some basic memory-management rules you shouldn't forget
Here are the fundamental rules when it comes to memory management:
- Any object you create using alloc or new, any method that contains copy, and any object you send a retain message to is yours - you own it. That means you're responsible for telling the memory-management system when you no longer need the object and that its memory can now be used elsewhere.
- Within a given block of code, the number of times you use new, copy, alloc, and retain should equal the number of times you use release and autorelease. You should think of memory management as consisting of pairs of messages. If you balance every alloc and every retain with a release, your object will eventually be freed up when you're done with it.
- When you assign an instance variable using an accessor with a property attribute of retain, retain is automatically invoked - that is, you now own the object. Implement a dealloc method to release the instance variables you own.
- Objects created any other way (through convenience constructors or other accessor methods) are not your problem.
If you have a solid background in Objective-C memory management (all three of you out there), following those rules should be straightforward or even obvious.
A direct correlation exists between the amount of free memory available and your application's performance. If the memory available to your application dwindles far enough, the system will be forced to terminate your application. To avoid such a fate, keep a few words of wisdom in mind:
- Minimize the amount of memory you use - make that a high priority of your implementation design.
- Be sure to use the memory-management functions.
- In other words, be sure to clean up after yourself, or the system will do it for you, and it won't be a pretty picture.