Object c init in the protocol

yesterday, a colleague asked why we should not declare the init (initWith ...: (...)) method in the protocol in order to force the implementing classes to supply such an initializer. I was very surprised by this question and, in my opinion, this is nonsense. But I could not find the final reason, but the declaration of the init method in the protocol leads to less flexibility for implementations.

Could you tell me a good reason why the init method should or should not be in the protocol?

Thanks!

+7
source share
2 answers

You define methods in the protocols so that your code can call methods implemented by others. The β€œcontract” between you and the developers implementing your protocol is as follows:

  • You will define the protocol,
  • Someone else is implementing your protocol,
  • Someone else creates an object that implements your protocol and passes it to you, therefore
  • You can call methods of your protocol without knowing their implementation.

To call the methods of your protocol, you need to have an instance of an object that implements it. The whole point of defining protocols removes from your code any knowledge about the class that implements your protocol: if you know which class you are going to get, you can also skip the protocol and go directly to the class. However, if you want to call your init , you either need to know the class, or someone must pass you the alloc -ed object on which init has not yet been called. None of the alternatives is a good idea - the first kills the goal of having protocols, and the second forces your subscribers to deal with partially initialized objects.

Note that this does not stop you from using non- init configuration methods in the protocol: if all objects must be configured using certain bits of information, let your users implement all the init they want and add configureWith:... to your protocol, letting you control the process of setting up an object without knowing its init method.

+6
source

I know several protocols in the iOS SDK that have init methods .... For example, the NSCoding protocol has - initWithCoder: the required method. I think this is normal practice.

+3
source

All Articles