29
init

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:

N​S​M​u​t​a​b​l​e​A​r​r​a​y​ ​*​t​h​i​n​g​s​ ​=​ ​[​[​N​S​M​u​t​a​b​l​e​A​r​r​a​y​ ​a​l​l​o​c​]​ ​i​n​i​t​]​;​

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.

Writing init methods

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.

Figure 29.1  Appliance and its subclass, OwnedAppliance

Appliance and its subclass, OwnedAppliance

Create a new file: an NSObject subclass named Appliance. In Appliance.h, create instance variables and property declarations for productName and voltage:

#​i​m​p​o​r​t​ ​<​F​o​u​n​d​a​t​i​o​n​/​F​o​u​n​d​a​t​i​o​n​.​h​>​

@​i​n​t​e​r​f​a​c​e​ ​A​p​p​l​i​a​n​c​e​ ​:​ ​N​S​O​b​j​e​c​t​ ​{​
 ​ ​ ​ ​N​S​S​t​r​i​n​g​ ​*​p​r​o​d​u​c​t​N​a​m​e​;​
 ​ ​ ​ ​i​n​t​ ​v​o​l​t​a​g​e​;​
}​
@​p​r​o​p​e​r​t​y​ ​(​c​o​p​y​)​ ​N​S​S​t​r​i​n​g​ ​*​p​r​o​d​u​c​t​N​a​m​e​;​
@​p​r​o​p​e​r​t​y​ ​i​n​t​ ​v​o​l​t​a​g​e​;​

@​e​n​d​

(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:

#​i​m​p​o​r​t​ ​"​A​p​p​l​i​a​n​c​e​.​h​"​

@​i​m​p​l​e​m​e​n​t​a​t​i​o​n​ ​A​p​p​l​i​a​n​c​e​

@​s​y​n​t​h​e​s​i​z​e​ ​p​r​o​d​u​c​t​N​a​m​e​,​ ​v​o​l​t​a​g​e​;​

.​.​.​

You would create an instance of Appliance like this:

A​p​p​l​i​a​n​c​e​ ​*​a​ ​=​ ​[​[​A​p​p​l​i​a​n​c​e​ ​a​l​l​o​c​]​ ​i​n​i​t​]​;​

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset