Using accessors

You have a perfectly good initializer for BNRAppliance, but let’s take a moment to look at a variation that you will see in other people’s code. We typically do a plain assignments in an initializer, but many programmers will use the accessor methods. Change initWithProductName: to do this:

-​ ​(​i​n​s​t​a​n​c​e​t​y​p​e​)​i​n​i​t​W​i​t​h​P​r​o​d​u​c​t​N​a​m​e​:​(​N​S​S​t​r​i​n​g​ ​*​)​p​n​
{​
 ​ ​ ​ ​/​/​ ​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​)​ ​{​

 ​ ​ ​ ​ ​ ​ ​ ​/​/​ ​S​e​t​ ​t​h​e​ ​p​r​o​d​u​c​t​ ​n​a​m​e​
 ​ ​ ​ ​ ​ ​ ​ ​[​s​e​l​f​ ​s​e​t​P​r​o​d​u​c​t​N​a​m​e​:​p​n​]​;​

 ​ ​ ​ ​ ​ ​ ​ ​/​/​ ​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​
 ​ ​ ​ ​ ​ ​ ​ ​[​s​e​l​f​ ​s​e​t​V​o​l​t​a​g​e​:​1​2​0​]​;​
 ​ ​ ​ ​}​
 ​ ​ ​ ​r​e​t​u​r​n​ ​s​e​l​f​;​
}​

In most cases, there is little reason to do one over the other, but it makes for a great argument. The argument goes like this: The assign guy says, You cannot use an accessor method in an init method! The accessor assumes that the object is ready for work, and it is not ready for work until after the init method is complete. Then the accessor method guy says, Oh, come on. In the real world that is almost never an issue. My accessor method might be taking care of other stuff for me. I use my accessor anytime I set that variable.

Either approach will work in the vast majority of cases. Build and run the program.

At Big Nerd Ranch, we tend to set the instance variables directly and we typically do the assignment and check for the superclass’s initializer in one line. Do this in your initWithProductName: method:

-​ ​(​i​n​s​t​a​n​c​e​t​y​p​e​)​i​n​i​t​W​i​t​h​P​r​o​d​u​c​t​N​a​m​e​:​(​N​S​S​t​r​i​n​g​ ​*​)​p​n​
{​
 ​ ​ ​ ​i​f​ ​(​s​e​l​f​ ​=​ ​[​s​u​p​e​r​ ​i​n​i​t​]​)​ ​{​

 ​ ​ ​ ​ ​ ​ ​ ​_​p​r​o​d​u​c​t​N​a​m​e​ ​=​ ​[​p​n​ ​c​o​p​y​]​;​
 ​ ​ ​ ​ ​ ​ ​ ​_​v​o​l​t​a​g​e​ ​=​ ​1​2​0​;​
 ​ ​ ​ ​}​
 ​ ​ ​ ​r​e​t​u​r​n​ ​s​e​l​f​;​
}​
..................Content has been hidden....................

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