Tell Membership

Sign up for the FREE Tell Membership and receive benefits that include the digital edition of Tell Magazine sent straight to your inbox, product giveaways, coupons and much more!

 
 

iPhone Developer Intervention Week 9: Memory Management

Sections: iPhone, iPhone OS, SDK and hacks, iPhone/iPod touch/iPad, iPod, iPod touch, Originals

0
Print Friendly

XCode IconAfter discussing iPhone file types last week, we can move on to memory management. On the current version of the iPhone, there is only 128MB of RAM, which is far lower than the usual 2+GB we see on desktop and laptop Macs. iPhone developers must keep this in mind when they are designing their games and writing their code in order to reduce the number of crashes and give the user a great experience with their app.

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.

0
Print Friendly

Leave a Reply

Your email address will not be published. Required fields are marked *

*