Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to handle Objective-C protocols that contain properties?
    primarykey
    data
    text
    <p>I've seen usage of Objective-C protocols get used in a fashion such as the following:</p> <pre><code>@protocol MyProtocol &lt;NSObject&gt; @required @property (readonly) NSString *title; @optional - (void) someMethod; @end </code></pre> <p>I've seen this format used instead of writing a concrete superclass that subclasses extend. The question is, if you conform to this protocol, do you need to synthesize the properties yourself? If you're extending a superclass, the answer is obviously no, you do not need to. But how does one deal with properties that a protocol requires to conform to?</p> <p>To my understanding, you still need to declare the instance variables in the header file of an object that conforms to a protocol that requires these properties. In that case, can we assume that they're just a guiding principle? CLearly the same isn't the case for a required method. The compiler will slap your wrist for excluding a required method that a protocol lists. What's the story behind properties though?</p> <p>Here's an example that generates a compile error (Note: I've trimmed the code which doesn't reflect upon the problem at hand):</p> <p>MyProtocol.h</p> <pre><code>@protocol MyProtocol &lt;NSObject&gt; @required @property (nonatomic, retain) id anObject; @optional </code></pre> <p>TestProtocolsViewController.h</p> <pre><code>- (void)iDoCoolStuff; @end #import &lt;MyProtocol.h&gt; @interface TestProtocolsViewController : UIViewController &lt;MyProtocol&gt; { } @end </code></pre> <p>TestProtocolsViewController.m</p> <pre><code>#import "TestProtocolsViewController.h" @implementation TestProtocolsViewController @synthesize anObject; // anObject doesn't exist, even though we conform to MyProtocol. - (void)dealloc { [anObject release]; //anObject doesn't exist, even though we conform to MyProtocol. [super dealloc]; } @end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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