一个类可以在Objective C中实现一个协议吗?

问题描述:

我有一个类NSDate,如果它可以实现一个协议我以前创建将是方便。这可能吗?这是什么正确的语法?

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?

是的,这是可能的。语法是:

Yes, that's possible. The syntax is:

@interface NSDate (CategoryName) <ProtocolName>
@end

@implementation NSDate (CategoryName)
@end

以下是 Apple的文档

也可以使用类扩展。我非常喜欢这个私人符合委托协议。这样做隐藏了来自公共接口的一些类的一些委托的实现细节,并从头中删除了依赖。

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.