使用Objective-C的method_invoke在ARC下调用void方法 [英] Using Objective-C's method_invoke to call a void method under ARC
问题描述
在iOS上,我尝试从Objective-C运行时使用method_invoke
函数(
On iOS, I'm attempting to use the method_invoke
function from the Objective-C runtime (reference) in order to call an Objective-C method that is declared with a return type of void
.
这在非ARC代码中可以正常工作,但是在启用ARC的情况下,调用objc_retain
中的方法后会崩溃.我认为这是发生了什么事,就是编译器注意到了method_invoke
的返回类型id
,并试图保留method_invoke
返回的值(请注意,method_invoke
旨在返回其返回值).调用.)
This works fine in non-ARC code, but with ARC enabled, I get a crash after the invocation of the method in objc_retain
. I think what's going on is that the compiler notices method_invoke
's return type of id
, and attempts to retain the value returned by method_invoke
(note that method_invoke
is meant to return the return value of the method it invokes).
让编译器知道在这种特定情况下,method_invoke
的返回值是垃圾且不应保留的正确方法是什么?以下内容似乎可行,但从概念上讲似乎是错误的:
What's the correct way to let the compiler know that in this specific case, the return value of method_invoke
is garbage and should not be retained? The following appears to work, but seems conceptually wrong:
(void)((__bridge void *)method_invoke(target, method));
(void)((__bridge void *)method_invoke(target, method));
这似乎不起作用(在objc_retain
中仍然崩溃:
This does not seem to work (still crashes in objc_retain
:
(void)method_invoke(target, method)
(void)method_invoke(target, method)
这里是否有更正确的方法?
Is there a more correct approach here?
推荐答案
This question actually gave me the idea for a better solution.
基本方法是创建引用具有正确签名(无效返回类型)的method_invoke
的函数指针,并将method_invoke
强制转换为该函数指针,然后通过该函数指针进行调用.
The basic approach was to create a function pointer referencing method_invoke
with the correct signature (void return type) and cast method_invoke
into this function pointer, and then call through the function pointer.
因此,大致而言:
static void (*_method_invoke_void)(id, Method, ...) = (void (*)(id, Method, ...)) method_invoke;
... snip ...
_method_invoke_void(target, method);
这篇关于使用Objective-C的method_invoke在ARC下调用void方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!