Chapter 6. More Objective-C

Now that all of the basic building blocks are in place, I can show you some of the more technical details of how Objective-C works. I’m going to fine-tune your code, talk more about reference counting, and then look at some unique features.

Most of the sections in this chapter describe techniques that you will use on a regular basis. A few of the topics are more advanced and you may not use them often, but if you need them, you really need them. All of them help you understand how Cocoa works.

More on Memory Management

In Chapter 5, I walked you through Objective-C’s traditional memory management system, called reference counting. Each object has a retain count, which is ostensibly the number of other things that are currently using it. The good news is that you don’t need to constantly check the retain count. You need to keep track of only your own references; Cocoa will do the rest.

Caution

You can call the retainCount method on any object, but don’t read too much into what it returns. It may not always reflect the exact number of retains and releases you have issued. Cocoa intervenes in certain cases.

The retain count starts at 1 when you create an object with alloc. It goes up and down as you call retain, release, and autorelease. When the retain count reaches 0, the Objective-C runtime will call dealloc on the object so that it can be removed from memory (see Figure 6-1).

Figure 6-1. When the retain count reaches 0, the dealloc method is called and the ...

Get Cocoa and Objective-C: Up and Running 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.