将协议作为方法参数传递
首先让我解释一下我的意思。我不想为协议输入参数:
-(void)someMethod:(id<SomeProtocol>)someArgument;
我真正想要的是将协议传递给方法,就像我可以将类传递给方法一样(以下内容是不正确的,但它希望解释我的意思)想做):
-(void)someMethod:(Protocol)someArgument;
然后我希望能够使用协议来检查一组对象是否实现它。
First let me explain what I don't mean. I don't want to type an argument to a protocol:
-(void)someMethod:(id<SomeProtocol>)someArgument;
What I do want to is to pass a protocol to a method in the same way I can pass a Class to a method (The following is incorrect, but it hopefully explains what I want to do):
-(void)someMethod:(Protocol)someArgument;
I would then like to be able to use the Protocol to check whether a set of objects implement it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您在编码时知道协议的名称,请使用
@protocol(SomeProtocol)
获取指向该协议的指针,类似于使用@selector(x)< /代码>。
除此之外,您只需使用类标识符
Protocol
引用协议 - 因此您的方法声明将如下所示:您可以在文档中查看
NSObjectconfesToProtocol 的示例:
<一href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/clm/NSObject/conformsToProtocol ">http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/clm/NSObject/conformsToProtocol :
If you know the name of a protocol at coding-time, use
@protocol(SomeProtocol)
to get a pointer to that protocol, similar to how you'd use@selector(x)
.Beyond that, you just refer to protocols with the class identifier
Protocol
-- so you're method declaration would look like:You can see an example in the docs for
NSObject conformsToProtocol:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/clm/NSObject/conformsToProtocol:
协议是一个类,因此您只需像任何其他对象类型一样编写
- (void)someMethod:(Protocol *)someArgument
。您可以在conformsToProtocol:
的声明中看到这一点:Protocol is a class, so you just write
- (void)someMethod:(Protocol *)someArgument
like with any other object type. You can see this in the declaration forconformsToProtocol:
:将协议传递给参数的唯一方法
因为id<..>意味着在传递抛出参数之前它需要符合该协议
the only way to pass protocol into an argument
because id<..> means it needs to conform to that protocol before pass throw the argument
我不建议使用协议。它将掩盖您的代码实际依赖的接口。使用
id*
。这实际上就是可可框架传递协议的方式。请原谅我使用的文字,如果我不这样做,它认为我正在尝试做 HTML。I don't recommend using protocol. It will obscure which interface your code actually relies on. Use
id<yourprotocol>*
. This is actually how the cocoa frameworks pass protocols. Forgive the use of words if I don't it thinks I'm trying to do HTML.