Creating Object Instances
One of the
principal functions of a class
object is to serve as a factory for creating new instances. When new
objects are created, memory is allocated and its instance variables
are initialized. This is accomplished by using the
alloc
method, defined by the
NSObject class, as follows:
Song song = [song alloc];
The alloc class method dynamically allocates
memory, sets the isa variable to a pointer to the
class’s class object, sets all other variables to 0,
and then returns the new object instance. This takes care of the
system level tasks that need to be performed when an object is
created, but doesn’t allow the object to properly
initialize itself. To give an opportunity for object-specific
initialization, the NSObject class provides the
init instance method. To fully create an instance
of the Song class, use the following code:
Song song = [[song alloc] init];
The init
method can be overridden in a subclass
to assign defaults to instance variables and to take care of other
tasks that need to be performed before an object is used.
Tip
You can call the alloc and init
methods by using separate lines of code. However, since object
allocation and initialization are interlinked, calling both methods
with one line of code is good practice.
When you override the
init method, the superclass’s
init method (or designated initializer, as covered in the next section) should always be called to ensure that the superclass is initialized properly. Initialization methods ...
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.
Read now
Unlock full access