O'Reilly logo

Programming iOS 4 by Matt Neuburg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to Write an Initializer

Now that you know about self and super and instance variables, we can return to a topic that I blithely skipped over earlier. I described how to initialize a newly minted instance by calling an initializer, and emphasized that you must always do so, but I said nothing about how to write an initializer in your own classes. You will wish to do so only when you want your class to provide a convenient initializer that goes beyond the functionality of the inherited initializers. Often your purpose will be to accept some parameters and use them to set the initial values of some instance variables.

For example, in our example of a Dog with a number, let’s say we don’t want any Dog instances to come into existence without a number; every Dog must have one. So having a value for its number ivar is a sine qua non of a Dog being instantiated in the first place. An initializer publicizes this rule and helps to enforce it — especially if it is the class’s designated initializer. So let’s decide that this initializer will be Dog’s designated initializer.

Moreover, let’s say that a Dog’s number should not be changed. Once the Dog has come into existence, along with a number, that number should remain attached to that Dog instance for as long as that Dog instance persists.

So delete the setNumber: method and its declaration, thus destroying any ability of other classes to set a Dog instance’s number after it has been initialized. Instead, we’re going to set a Dog’s number ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required