Skip to Main Content
Objective-C® For Dummies®
book

Objective-C® For Dummies®

by Neal Goldstein
October 2009
Beginner content levelBeginner
456 pages
8h 59m
English
For Dummies
Content preview from Objective-C® For Dummies®

Chapter 12. The Birth of an Object

In This Chapter

  • How objects are created

  • What it means to allocate an object

  • The standard way to do initialization

  • Initialization and superclasses and subclasses

Up until now, you have been doing initialization on an ad hoc basis, using initialization methods such as these:

- (void) createTransaction: (double) theAmount
                            forBudget: (Budget*) aBudget;
- (void) createBudget: (double) aBudget
                withExchangeRate: (float) anExchangeRate;

There is a standard way to do initialization, however — one designed to work in a class hierarchy that ensures all of the super- and subclasses are initialized properly.

In this chapter, I show you the how to implement these standard initialization methods. First, though, you must allocate memory for the new object, as described in the first section of this chapter.

Allocating Objects

To create an object in Objective-C, you must do the following:

  1. Allocate memory for the new object.

  2. Initialize the newly allocated memory, as described in the next section.

Allocation (alloc) starts the process of creating a new object by getting the amount of memory it needs from the operating system to hold all of the object's instance variables. The alloc message is sent to the NSObject class, from which all of the classes you are using are derived. But not only does the alloc method allocate the memory for the object; it also initializes all the memory it allocates to 0 — all the ints are 0; all the floats become 0.0; all the pointers are nil; and the ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Objective-C

Objective-C

Jiva DeVoe
Cocoa in a Nutshell

Cocoa in a Nutshell

Michael Beam, James Duncan Davidson

Publisher Resources

ISBN: 9780470522752Purchase book