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:
Allocate memory for the new object.
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 int
s are 0; all the float
s become 0.0; all the pointers are nil
; and the ...
Get Objective-C® For Dummies® 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.