在 respondsToSelector if 语句后调用类型 id 上的方法时发出警告
我相当确定这是一个简单的问题,但我一直无法解决。
我在 if 语句中使用 respondsToSelector
方法来检查委托是否实现了方法。在 if 语句中我调用这个选择器。没什么复杂的。但我收到一条警告,指出找不到该方法(屏幕截图)。但是,如果我包含实现该方法的类的头文件,则警告就会消失。
我怀疑这可能与源代码的编译顺序有关?
非常感谢任何帮助。
I'm fairly sure this is a simple issue but it's something that I've been unable to solve.
I am using the respondsToSelector
method in an if statement to check whether a delegate implements a method. Inside the if statement I then call this selector. Nothing complex. But I get a warning saying the method is not found, (Screenshot). If however I include the header file for the class that implements the method, the warning goes away.
I suspect it could be to do with the order the sources are compiled perhaps?
Any help much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尽管您可以使用 @selector(somethingHere:) 创建任意选择器,但您无法在没有编译器警告的情况下对
id
变量调用任意方法。编译器仍然会检查您正在调用的方法/选择器是否已在类或类别的某处定义。您需要包含适当的标头,以便编译器知道系统中存在可以响应该方法的对象/类,否则您可能会错误输入选择器并且永远不知道它。
编辑:
好的,我现在看到您正在实现委托。在这种情况下,您需要使用适当的方法声明协议,并为您的委托使用类型 id。然后你的类应该被声明为实现该协议。
Although you can create arbitrary selectors using
@selector(somethingHere:)
, you cannot call arbitrary methods on anid
variable without a compiler warning. The compiler will still check that the method/selector you are calling has been defined somewhere on a class or category.You need to include the appropriate header so the compiler knows that there are objects/classes in the system that can respond to that method, otherwise you could mistype a selector and never know about it.
edit:
OK I see now that you are implementing a delegate. In that case you need to declare a protocol with the appropriate methods, and use the type
id<ProtocolName>
for your delegate. Then your class should be declared as implementing that protocol.如果您想隐藏 id 数据类型后面的真实类,请编写 someProtocol 并在 ivars 中定义 _delegate 并指定它实现该协议的内容。
If you want to hide real class behind id data type, than write someProtocol and than define _delegate in ivars and specify what it implements that protocol.
确保您已在协议中声明了该方法。
Make sure you have declared the method in the protocol.