extend a protocol privately using a category in ob

2019-07-02 02:39发布

did some searching and didn't find much, but wondering if it's possible to extend a protocol.

Currently, in MyDelegate.h, there is:

@protocol MyDelegate <NSObject>

hoping to create a private header, MyDelegate+Private.h, to not expose extra optional methods to the client.

@protocol MyDelegate (Private) <NSObject>

this doesn't seem to work. is it possible? would like to avoid creating a whole new delegate protocol that holds a superset of the current one.

1条回答
霸刀☆藐视天下
2楼-- · 2019-07-02 03:27

I don't think you can create a category on a protocol, but you can create a protocol using a protocol and keep it in a private header. Apple has done this quite frequently in its frameworks.

@protocol MyDelegate_Private <MyDelegate>
- (void)myRequiredPrivateMethod;
@optional
- (void)myOptionalPrivateMethod;
@end

Then you specify this protocol when declaring the class. To hide the fact that there is a private protocol, use a public header which declares the class as implementing the public protocol and a private header which declares it as implementing the private protocol.

Also, if you only use optional methods in the protocol, you don't really need to make a protocol. All it does is specify the list of methods which could be implemented, and since it is only used privately that isn't necessary. You could just say the class implements the public protocol and "just happens" to also implement these other methods which aren't included in the interface.

查看更多
登录 后发表回答