Note that there are some explanatory texts on larger screens.

plurals
  1. PODefining categories for protocols in Objective-C?
    text
    copied!<p>In Objective-C, I can add methods to existing classes with a category, e.g.</p> <pre><code>@interface NSString (MyCategory) - (BOOL) startsWith: (NSString*) prefix; @end </code></pre> <p>Is it also possible to do this with protocols, i.e. if there was a NSString protocol, something like:</p> <pre><code>@interface &lt;NSString&gt; (MyCategory) - (BOOL) startsWith: (NSString*) prefix; @end </code></pre> <p>I want to do this since I have several extensions to NSObject (the class), using only public NSObject methods, and I want those extensions also to work with objects implementing the protocol .</p> <p>To give a further example, what if I want to write a method logDescription that prints an object's description to the log:</p> <pre><code>- (void) logDescription { NSLog(@"%@", [self description]); } </code></pre> <p>I can of course add this method to NSObject, but there are other classes that do not inherit from NSObject, where I'd also like to have this method, e.g. NSProxy. Since the method only uses public members of protocol , it would be best to add it to the protocol.</p> <p>Edit: Java 8 now has this with "virtual extension methods" in interfaces: <a href="http://cr.openjdk.java.net/~briangoetz/lambda/Defender%20Methods%20v4.pdf" rel="noreferrer">http://cr.openjdk.java.net/~briangoetz/lambda/Defender%20Methods%20v4.pdf</a>. This is exactly what I would like to do in Objective-C. I did not see this question earning this much attention...</p> <p>Regards, Jochen</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