Managing Memory

If you take a look at your class's accessors for exclamationCount and originalString, you'll see some new methods being called on the instance variables. The retain, copy, and release messages are extremely important: You use them to manage the memory usage of objects.

Note

Memory is also one of the more complicated things to understand about Objective-C, so don't get frustrated if you don't understand it at first.

As you learned before, thousands of objects are created and deleted every second that you're using your iPhone. And each of those objects uses a chunk of memory, which is a precious resource on a mobile device. Your desktop computer may measure its memory capacity in gigabytes, but your phone only has a few hundred megabytes.

If you're not careful about your memory usage, the iPhone's operating system will shut down your application. If it didn't, the system would eventually grind to a halt, and you'd have to reboot your phone. That's kind of inconvenient when you're expecting an important call.

So how is memory managed with these –retain, –release, and –copy methods?

Every object in memory maintains a counter. This counter keeps track of how many other objects are using the object. When you want to use an object, you must tell the object, so it can update its counter, and you do so by using the –retain message. After you send that message, the object updates its retain count, and that object won't be deleted. If you're ever interested in how many other ...

Get iPhone App Development: The Missing Manual now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.