NSInvocation with primitive使用getReturnValue

时间:2015-02-13 12:09:34

标签: ios objective-c nsinvocation

我们有以下方法,适用于对象。它接受一个对象的方法,并将结果放在returnValueContainer:

+ (void)invokePrivateMethod:(SEL)selector returnValueContainer:(NSObject **)returnValueContainer onObject:(NSObject *)object {
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[object class] instanceMethodSignatureForSelector:selector]];
    [invocation setSelector:selector];
    [invocation setTarget:object];
    [invocation invoke];
    [invocation getReturnValue:returnValueContainer];
}

是否有可能以某种方式修改它,以便我们可以返回基元(例如NSInteger)以及getReturnValue中的对象?

背景:我们正在尝试访问类的私有原始属性以进行单元测试。

1 个答案:

答案 0 :(得分:3)

如果您想使用int进行操作,只需将其更改为returnValueContainer:(int *)returnValueContainer即可。如果你希望它适用于所有类型,你可以只做returnValueContainer:(void *)returnValueContainer并让调用者传入指向正确类型的指针。

(顺便说一句,你在NSObject **做什么在ARC中不正确。NSObject **类型的参数隐含地表示NSObject * __autoreleasing *。但正确的类型应该是{{1因为NSObject * __unsafe_unretained *只是将指向缓冲区的缓冲区视为一个普通的字节缓冲区,而不知道任何有关内存管理的内容。它不会像getReturnValue:类型那样保留和自动释放它。在大多数情况下它赢了没有区别(并且调用的方法可能会自动释放它),有些情况下它会很重要。)