In the NSObject class, there is a method named init. Using init looks like this:
NSMutableArray *things = [[NSMutableArray alloc] init];
You send the init message to the new instance so that it can initialize its instance variables to usable values; alloc creates the space for an object, and init makes the object ready to work. 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: BNRAppliance and BNROwnedAppliance (a subclass of BNRAppliance). An instance of BNRAppliance will have a productName and a voltage. An instance of BNROwnedAppliance will also have a set containing the names of its owners.
Create a new file: an NSObject subclass named BNRAppliance. In BNRAppliance.h, create property declarations for productName and voltage:
#import <Foundation/Foundation.h> @interface BNRAppliance : NSObject @property (nonatomic, copy) NSString *productName; @property (nonatomic) int voltage; @end
You would create an instance of BNRAppliance like this:
BNRAppliance *a = [[BNRAppliance alloc] init];
Note that because BNRAppliance does not implement an init method, it will execute the init method defined in NSObject. When this happens, all the instance variables specific to BNRAppliance are zeroed out. Thus, the productName of a new instance of BNRAppliance will be nil, and voltage will be zero.