Deadly init methods

Every once in a while, however, you can’t safely override the superclass’s designated initializer. Let’s say that you are creating a subclass of NSObject called WallSafe, and its designated initializer is initWithSecretCode:. However, having a default value for secretCode is not secure enough for your application. This means that the pattern we have been using – overriding init to call the new class’s designated initializer with default values – is not acceptable.

So what do you do? An instance of WallSafe will still respond to an init message. Someone could easily do this:

W​a​l​l​S​a​f​e​ ​*​w​s​ ​=​ ​[​[​W​a​l​l​S​a​f​e​ ​a​l​l​o​c​]​ ​i​n​i​t​]​;​

The best thing to do is to override the superclass’s designated initializer in a way that lets developers know that they have made a mistake and tells them how to fix it:

-​ ​(​i​d​)​i​n​i​t​
{​
 ​ ​ ​ ​@​t​h​r​o​w​ ​[​N​S​E​x​c​e​p​t​i​o​n​ ​e​x​c​e​p​t​i​o​n​W​i​t​h​N​a​m​e​:​@​"​W​a​l​l​S​a​f​e​I​n​i​t​i​a​l​i​z​a​t​i​o​n​"​
 ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​r​e​a​s​o​n​:​@​"​U​s​e​ ​i​n​i​t​W​i​t​h​S​e​c​r​e​t​C​o​d​e​:​,​ ​n​o​t​ ​i​n​i​t​"​
 ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​u​s​e​r​I​n​f​o​:​n​i​l​]​;​
}​
..................Content has been hidden....................

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