Deadly init methods

Every once in a while, however, you cannot safely override the superclass’s designated initializer. Let’s say that you are creating a subclass of NSObject called BNRWallSafe, 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 BNRWallSafe will still respond to an init message. Someone could easily do this:

B​N​R​W​a​l​l​S​a​f​e​ ​*​w​s​ ​=​ ​[​[​B​N​R​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 ...

Get Objective-C Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.