检查一个对象是否符合 Objective-C 中的两个单独的协议
在 Objective-C 中,当你声明一个实例变量时,你可以在编译时检查它是否符合分配协议,如下所示:
id <MyProtocol> variable;
Is it possible to check if a object allocates to the variableconsole to meet multiple differentprotocol atcompile time?如:
id <MyProtocol, MyOtherProtocol> variable;
我知道我可以使用 conformsToProtocol:
和 respondsToSelector
等进行运行时检查(我在实际使用该对象之前执行此操作以提高安全性),并且我可以编写我自己的 setter 方法可以进行检查,但我想在编译时知道。
In Objective-C when you declare an instance variable you can check if it conforms to a protocol on assignment at compile time like so:
id <MyProtocol> variable;
Is it possible to check whether an object assigned to the variable conforms to two separate protocols at compile time? As in:
id <MyProtocol, MyOtherProtocol> variable;
I know I can do runtime checking using conformsToProtocol:
and respondsToSelector
et al, (which I do before actually using the object for added safety), and I could write my own setter method that does the check, but I'd like to know at compile time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,该语法是正确的。
检查对象是否符合协议的正确方法是这样做:
请注意,这既可以用作实例方法,也可以用作类方法。
如果由于某种奇怪的原因您无法使用
conformsToProtocol:
,您可以下降到运行时级别:Yes, that syntax is correct.
The correct way to check if an object conforms to a protocol is to do this:
Note that this works as both an instance method and a class method.
If for some bizarre reason you can't use the
conformsToProtocol:
, you can drop down to the runtime level:我认为最好是使用自己的代码:
并且在调用方法之前,检查变量是否响应您想要调用的内容:
由于 Objective-C 是动态语言,仅声明变量协议并不能保证它符合到协议。当你构建时它主要会生成警告。
I think the best is to use your own code:
And before calling a method, check if the variable responds to what you want to call:
Since Objective-C is a dynamic language, just declaring the variable protocol can't assure that it conforms to the protocol. It'll mostly generates warnings when you build.
您不能总是在编译时检查协议一致性,因为从编译器的角度来看,(非限定)类型
id
的对象始终是有效对象。例如,话虽这么说,如果对象不符合编译时已知的两个协议,
将会向您发出警告 -时间:You can’t always check protocol conformance in compile-time because an object of (non-qualified) type
id
is always a valid object from the compiler’s perspective. For instance,That being said,
<P1, P2>
will give you warnings in case the object doesn’t conform to both protocols if that can be known at compile-time: