Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
In some cases, an initial value of zero for your instance variables may work fine. In others, however, you’ll need instances of your class to come into the world with their instance variables initialized to non-zero values.
Let’s say that every instance of Appliance should start its life with a voltage of 120. In Appliance.m, override NSObject’s init method by adding a new implementation of init.
- (id)init
{
// Call the NSObject's init method
self = [super init];
// Give voltage a starting value
voltage = 120;
// Return a pointer to the new object
return self;
}
Now when you create a new instance of Appliance, it will have a voltage of 120 by default. (Note that this doesn’t change anything about the accessor methods. After the instance is initialized, it can be changed just as before using setVoltage:.)