一个类可以同时实现协议吗? [英] Can a category simultaneously implement a protocol?
问题描述
如果我为一个类创建的类别添加了也满足协议规定的契约的方法,我想将该类别标记为实现协议,从而指示Obj-C预处理,
示例委托(为了清楚起见,感谢Ole!):
@protocol SomeDelegate< NSObject>
- (void)someDelegateMessage;
@end
示例类别:
@interface NSObject(SomeCategory)< SomeDelegate>
- (void)someDelegateMessage;
@end
而且是典型的实现
@implement NSObject(SomeCategory)
- (void)someDelegateMessage {}
@end
当我真的尝试这个,我得到一个警告每个NSObject方法:
警告:类别SomeCategory未完成实施
警告:找不到-description的方法定义
$ b b...
警告:未找到-isEqual:的方法定义
警告:category'SomeCategory'没有完全实现NSObject协议
如果我移除 SomeDelegate>
,但当然NSObject不被认为是SomeDelegate
解决方法是在没有实现的类别上声明协议,并在不同的类别中实现该方法,例如:
@interface NSObject(SomeCategory)< SomeDelegate>
pre>
- (void)someDelegateMessage;
@end
@implementation NSObject(SomeCategory_Impl)
- (void)someDelegateMessage {}
@end
如果这样做,
NSObject
将被视为符合< SomeDelegate >
,并且对someDelegateMessage
的运行时检查将成功。但是,conformsToProtocol:
运行时检查将失败。
当然,你应该提交错误请求在核心类上声明的方法不会生成警告。
If a category I'm creating for a class adds methods that also fulfill the contract set out by a protocol, I'd like to flag that category class as implementing the protocol, and thereby indicate to the Obj-C pre-processor that the class effectively implements the protocol as well.
Example delegate (for clarity, thanks Ole!):
@protocol SomeDelegate <NSObject> - (void)someDelegateMessage; @end
Example category:
@interface NSObject (SomeCategory) <SomeDelegate> - (void)someDelegateMessage; @end
And with an otherwise typical implementation
@implement NSObject (SomeCategory) - (void)someDelegateMessage {} @end
When I actually try this, I get a warning for each NSObject method:
warning: incomplete implementation of category 'SomeCategory'
warning: method definition for '-description' not found
...
warning: method definition for '-isEqual:' not found
warning: category 'SomeCategory' does not fully implement the 'NSObject' protocol
Works fine if I remove
<SomeDelegate>
from the declaration, but of course NSObject isn't recognized as a SomeDelegate解决方案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 forsomeDelegateMessage
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.
这篇关于一个类可以同时实现协议吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!