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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With