Objective-C 动态创建的方法和编译器警告
如果我在运行时动态生成方法然后调用它们 - 如何说服编译器该类将响应未声明(生成)的方法并使其不会抛出警告?
更新有关答案
当我生成方法时 - 它们的名称在编译时未知。举个例子 - 如果我有一个视图控制器 MyFooController
并且它是用方法 initWithFoo:(Foo*)foo
启动的,我就能够生成像 这样的方法>pushMyFooControllerWithFoo:(Foo *)foo
用于 UINavigationController
。因此,您会注意到声明此类方法会适得其反。
If I generate methods dynamically on runtime and then call them - how can I convince compiler that the class will respond to undeclared (generated) methods and make it not throw warnings?
Update in regard to answers
When I generate the methods - their name is not known at compile time. To give an example - if I have a view controller MyFooController
and it's initiated with method initWithFoo:(Foo*)foo
, I'd be able to generate method like pushMyFooControllerWithFoo:(Foo *)foo
for UINavigationController
. Hence you notice that declaring such methods would be counter-productive.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这并不能直接回答您的问题,但如果我生成方法名称(大概是从字符串),我会使用字符串名称来调用它们,从而绕过编译器警告。
这样您就需要对生成的方法名称的有效性负责。
This doesn't directly answer your question, but if I was generating method names (presumably from strings), I would call them using the string names, hence bypassing the compiler warnings.
That way you are responsible for the validity of the generated method names.
由于您是在运行时添加方法,因此您还应该使用运行时函数调用它们,例如
objc_msgSend
或performSelector:withObject:
,这样编译器就不会警告您任何事物。Since you are adding methods on runtime, so you should also invoke them with runtime function,
objc_msgSend
orperformSelector:withObject:
for example, so the compiler will not going to warn you anything.好吧,如果你打电话给他们,你就知道他们的签名,如果你知道他们的签名,你就可以声明他们,不是吗?
Well, if you call them, you know their signature, and if you know their signature, you can declare them, can't you?
在 NSObject 的类别中声明此方法并创建一个空实现:
在您的对象中,您可以调用它而不会出现任何警告:
然后动态生成
[MyObject doSomething]
的实现,它将被调用而不是NSObject 的
之一。更新:
或者,可以在对象的类别中声明该方法。这会抑制编译器的实现不完整警告。但是,我认为这不是一个好的解决方法,因为如果在调用方法之前没有在运行时动态创建该方法,应用程序将会崩溃。
Declare this method in a category for NSObject and make an empty implementation:
In your object you can call it without any warnings:
Then generate implementation of
[MyObject doSomething]
dynamically, it will be called instead ofNSObject's
one.Update:
Alternatively, the method can be declared in a category for the object. This suppresses the compiler's Incomplete implementation warning. However, I think this is not a good workaround, because the application will crash if the method is not created dynamically in runtime before it is called.