Can a category simultaneously implement a protocol?

ε祈祈猫儿з 提交于 2019-12-03 22:11:11

A workaround is to declare the protocol on a category with no implementation, and implement the method in a different category, e.g.:

@interface NSObject (SomeCategory) <SomeDelegate>
  - (void)someDelegateMessage;    
@end

@implementation NSObject (SomeCategory_Impl)
  - (void)someDelegateMessage {}
@end

If you do this, NSObject will be considered to conform to <SomeDelegate> at compile time, and runtime checks for someDelegateMessage will succeed. However, conformsToProtocol: runtime checks will fail.

Of course, you should file a bug requesting that methods declared on the core class don’t generate warnings.

Any chance your protocol declaration includes the NSObject protocol? Like this:

@protocol SomeDelegate <NSObject>
...

That's where the warnings are coming from because now your category does not implement the full protocol. In the test code I just typed up, removing NSObject from the protocol removes the compiler warnings.

If you want the compiler to shut up about sending <NSObject> messages (and its important that you remember that thats the protocol name, not the class name) then just use 'id' variables, not 'id' since thats you explicitly telling the compiler "This is an object which only implements the SomeDelegate protocol".

Alternately, use NSObject as your variable type instead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!