In the class NSObject, there is a method named init. After an object has been allocated, you send the init message to the new instance so that it can initialize its instance variables to usable values. So alloc creates the space for an object, and init makes the object ready to work. Using init looks like this:
NSMutableArray *things = [[NSMutableArray alloc] init];
Notice that init is an instance method that returns the address of the initialized object. It is the initializer for NSObject. This chapter is about how to write initializers.
Create a new project: a Foundation Command Line Tool called Appliances. In this program, you are going to create two classes: Appliance and OwnedAppliance (a subclass of Appliance). An instance of Appliance will have a productName and a voltage. An instance of OwnedAppliance will also have a set containing the names of its owners.
Create a new file: an NSObject subclass named Appliance. In Appliance.h, create instance variables and property declarations for productName and voltage:
#import <Foundation/Foundation.h> @interface Appliance : NSObject { NSString *productName; int voltage; } @property (copy) NSString *productName; @property int voltage; @end
(We’ll talk about the copy property attribute in Chapter 30.)
In Appliance.m, synthesize the properties to create the accessor methods for the instance variables:
#import "Appliance.h" @implementation Appliance @synthesize productName, voltage; ...
You would create an instance of Appliance like this:
Appliance *a = [[Appliance alloc] init];
Note that because Appliance doesn’t implement an init method, it will execute the init method defined in NSObject. When this happens, all the instance variables specific to Appliance are zero-ed out. Thus, the productName of a new instance of Appliance will be nil, and voltage will be zero.