Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a category implement a protocol in Objective C?

I have a category on NSDate and it would be convenient if it could implement a protocol I previously created. Is this possible? what's the correct syntax for this?

like image 743
cfischer Avatar asked Apr 28 '11 20:04

cfischer


People also ask

What is the use of category in Objective-C?

Categories provide the ability to add functionality to an object without subclassing or changing the actual object. A handy tool, they are often used to add methods to existing classes, such as NSString or your own custom objects.

How do you make a class conform to a protocol in Objective-C?

Objective-C Language Protocols Conforming to Protocols It is also possible for a class to conform to multiple protocols, by separating them with comma. Like when conforming to a single protocol, the class must implement each required method of each protocols, and each optional method you choose to implement.

CAN protocols have properties Objective-C?

You can have properties in a protocol, provided every class that conforms to your protocol have a corresponding @synthesize for that property, or provide a getter and setter.


1 Answers

Yes, that's possible. The syntax is:

@interface NSDate (CategoryName) <ProtocolName>
@end

@implementation NSDate (CategoryName)
@end

Here's Apple's documentation on the topic.

It's also possible to do this using a class extension. I very much like this to privately conform to delegate protocols. Doing so hides the implementation detail of being some delegate of some class from the public interface and removes the dependency from the header.

like image 62
Nikolai Ruhe Avatar answered Oct 13 '22 15:10

Nikolai Ruhe