iPhone Developer Intervention Week 9: Memory Management
by at May 26, 2009 3:08 pm
Sections: iPhone, iPhone OS, SDK and hacks, iPhone/iPod touch/iPad, iPod, iPod touch, Originals
Sections: iPhone, iPhone OS, SDK and hacks, iPhone/iPod touch/iPad, iPod, iPod touch, Originals

In Objective C, objects are initialized and allocated before they can be used. For example, when declaring a UIElement, you write something like UISlider *mySlider = [[UISlider alloc] init] in order to be able to use it. On the back end, this reserves a chunk of memory to hold that slider and any other data associated with it—such as its state or value. This memory will stay there forever (and potentially cause leaks) unless the developer remembers to release the object when they are done using it. This is done simply by writing [mySlider release] once it is no longer needed.
It may be worth explaining what is going on in the back end with memory. When the object is first created, its memory count is bumped up to 1. Objects will remain in memory until this count reaches 0. However, a developer may want to release it in one area but still use the object in another. That’s where the retain call comes in ([mySlider retain]). Each time retain is called on an object, the memory count adds 1. The only way to completely destroy an object in memory is to bump the memory count back down to 0, so it is said that the amount of retains/allocs in code must equal the amount of releases in order to ensure this.
Memory leaks can be especially important to watch on the iPhone for a couple reasons. For one, there is only 128MB of RAM, as I mentioned before. Furthermore, if your app requires all of that RAM to functional normally, you may have issues when iPod.app or Mail.app is running in the background on your customer’s phone, as those also require some of the memory. Therefore, writing efficient code has never been as important than it is with the iPhone. It’s both a challenge and a good learning experience, if you ask me.
See more iPhone Developer Intervention articles.
Related Posts