33
init

In the NSObject class, there is a method named init. 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​]​;​

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.

Writing init methods

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.

Figure 33.1  BNRAppliance and its subclass, BNROwnedAppliance

BNRAppliance and its subclass, BNROwnedAppliance

Create a new file: an NSObject subclass named BNRAppliance. In BNRAppliance.h, create 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​ ​B​N​R​A​p​p​l​i​a​n​c​e​ ​:​ ​N​S​O​b​j​e​c​t​

@​p​r​o​p​e​r​t​y​ ​(​n​o​n​a​t​o​m​i​c​,​ ​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​ ​(​n​o​n​a​t​o​m​i​c​)​ ​i​n​t​ ​v​o​l​t​a​g​e​;​

@​e​n​d​

You would create an instance of BNRAppliance like this:

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

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.

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

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