A basic init method

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.

-​ ​(​i​d​)​i​n​i​t​
{​
 ​ ​ ​ ​/​/​ ​C​a​l​l​ ​t​h​e​ ​N​S​O​b​j​e​c​t​'​s​ ​i​n​i​t​ ​m​e​t​h​o​d​
 ​ ​ ​ ​s​e​l​f​ ​=​ ​[​s​u​p​e​r​ ​i​n​i​t​]​;​

 ​ ​ ​ ​/​/​ ​G​i​v​e​ ​v​o​l​t​a​g​e​ ​a​ ​s​t​a​r​t​i​n​g​ ​v​a​l​u​e​
 ​ ​ ​ ​v​o​l​t​a​g​e​ ​=​ ​1​2​0​;​

 ​ ​ ​ ​/​/​ ​R​e​t​u​r​n​ ​a​ ​p​o​i​n​t​e​r​ ​t​o​ ​t​h​e​ ​n​e​w​ ​o​b​j​e​c​t​
 ​ ​ ​ ​r​e​t​u​r​n​ ​s​e​l​f​;​
}​

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:.)

Notice that you called the superclass’s init method, which initializes the instance variables declared in the superclass and returns a pointer to the initialized object. Most of the time, this works flawlessly. However, a few classes have deviant init methods. Here are the two possible forms of deviance:

  • The init method figures out a clever optimization that it can do, deallocates the original object, allocates a different object, and returns the new object.

  • The init method fails, deallocates the object, and returns nil.

To deal with the first case, Apple requires that you set self to point to the object returned from the superclass’s init method. You did this in the first line of your init method.

To deal with the second case, Apple recommends that you check that your superclass’s initializer returns a valid object and not nil. After all, there’s no point in performing custom set-up on an object that doesn’t exist. Change your init method to match Apple’s recommendation:

-​ ​(​i​d​)​i​n​i​t​
{​
 ​ ​ ​ ​/​/​ ​C​a​l​l​ ​N​S​O​b​j​e​c​t​'​s​ ​i​n​i​t​ ​m​e​t​h​o​d​
 ​ ​ ​ ​s​e​l​f​ ​=​ ​[​s​u​p​e​r​ ​i​n​i​t​]​;​

 ​ ​ ​ ​/​/​ ​D​i​d​ ​i​t​ ​r​e​t​u​r​n​ ​s​o​m​e​t​h​i​n​g​ ​n​o​n​-​n​i​l​?​
 ​ ​ ​ ​i​f​ ​(​s​e​l​f​)​ ​{​

 ​ ​ ​ ​ ​ ​ ​ ​/​/​ ​G​i​v​e​ ​v​o​l​t​a​g​e​ ​a​ ​s​t​a​r​t​i​n​g​ ​v​a​l​u​e​
 ​ ​ ​ ​ ​ ​ ​ ​v​o​l​t​a​g​e​ ​=​ ​1​2​0​;​
 ​ ​ ​ ​}​
 ​ ​ ​ ​r​e​t​u​r​n​ ​s​e​l​f​;​
}​

Truthfully, these sorts of checks are only necessary in a couple of very specific cases. Thus, in practice, many Objective-C programmers often skip the extra checks. In this book, however, we will always do the checks because it is the Apple-approved way to implement init methods.

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

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