Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You define methods in protocols so that your code could call methods implemented by others. The "contract" between you and developers implementing your protocol looks like this:</p> <ul> <li><strong>You</strong> define the protocol,</li> <li><strong>Someone else</strong> implements your protocol,</li> <li><strong>Someone else</strong> creates an object implementing your protocol, and gives it to you, so</li> <li><strong>You</strong> can call methods of your protocol without knowing their implementation.</li> </ul> <p>In order to call methods of your protocol, you need to have an instance of an object implementing it. The whole point of defining protocols is removing from your code any knowledge about the class implementing your protocol: if you know which class you are going to get, you might as well skip the protocol, and program to the class directly. However, if you want to call your <code>init</code>, you have to either know the class, or someone else must pass you an <code>alloc</code>-ed object on which the <code>init</code> has not been called yet. Neither alternative is a good idea - the first one kills the purpose of having protocols, and the second forces your callers deal in partially initialized objects.</p> <p>Note that it does not prevent you from having non-<code>init</code> configuration methods in a protocol: if all objects must be configured using certain bits of information, let your users implement whatever <code>init</code> that they want, and add a <code>configureWith:...</code> method to your protocol, letting you control the process of configuring the object without knowing about its <code>init</code> method.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload