Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would a class ever have more than one designated initializer?

Reading through Apple's documentation on Tips and Techniques for Framework Developers, I came across this statement about designated initializers:

A designated initializer is an init method of a class that invokes an init method of the superclass. (Other initializers invoke the init methods defined by the class.) Every public class should have one or more designated initializers.

(Emphasis added.)

Based on my understanding—and indeed, the very use of the word "designated"—a class should have only one designated initializer. But according to the documentation, multiple designated initializers are acceptable.

Assuming that you have two (or more) designated initializers, their role is to call the superclass's designated initializer in order to guarantee proper object initialization. But if both designated initializers are calling the same superclass's designated initializer, then why was there the need for more than one in the first place? Shouldn't the class be refactored to funnel all the other init methods to the singular designated initializer?

I'm just a bit confused as to what use case or design pattern would call for multiple designated initializers?

like image 248
CIFilter Avatar asked Sep 21 '11 14:09

CIFilter


1 Answers

You would do this when you want to have a different initialization for different objects of the same class. One example is class clusters, like NSNumber. It has quite a few initializers for the different types of numbers they can hold. To provide the most accurate representation, the class should hold its value in the same format it received it in, instead of casting. This means the initializers can't simply call a common initializer and return. They need to do some custom work. This makes them a designated initializer.

Another example would be a document class which needs to do some initialization only for new files and some other initialization only for documents being opened. Both of these initializers will call their super implementation, which in turn calls the plain init method to do common initialization. However, since they do more than simply calling another initializer with a default value, they are considered designated initializers.

like image 187
ughoavgfhw Avatar answered Sep 22 '22 05:09

ughoavgfhw