【发布时间】:2014-04-21 18:19:47
【问题描述】:
我正在使用 NSProxy 子类和 forwardInvocation: 来捕获对我的后端 API 对象(共享实例)的调用。
一些背景信息: 我想捕获 API 调用,以便每次都可以检查是否必须刷新身份验证令牌。如果是,我只是在之前执行刷新。
方法参数(invocation)包含块。
一些简化的代码:
- (void)forwardInvocation:(NSInvocation *)invocation {
[invocation setTarget:self.realAPI];
[invocation retainArguments];
// Perform refresh call and forward invocation after
// successfully refreshed
if (authenticationRefreshNeeded) {
[self.realAPI refreshWithBlock:^(NSObject *someObject) {
[invocation invokeWithTarget:self.realAPI];
}];
}
// Otherwise we just forward the invocation immediately
else {
[invocation invokeWithTarget:self.realAPI];
}
return;
}
我已经在调用retainArguments,所以我的块和其他参数不会因为invokeWithTarget: 的延迟执行而丢失(refreshWithBlock: 进行异步 API 调用)。
到目前为止一切正常 - 但是:
在刷新块内执行invokeWithTarget: 时,调用的返回值始终为nil。有什么方法可以保留返回值(如参数)?
有什么提示吗?建议?
更新
作为对@quellish 的回应:
问题是返回值是NSURLSessionDataTask 类型(我用来显示活动指示器),我在调用后直接读取它。但是代理不会立即转发呼叫,因此返回值不存在 - 当然(我是盲目的)。
什么是可能的解决方法?我可以返回占位符值吗?或者当方法被调用时我如何知道调用者,以便稍后检索返回值?
【问题讨论】:
-
你能用你在哪里/如何读取返回值来更新这个问题吗?当您调用
getReturnValue:时,您的调用本身是否为零? -
这样做了。晚上剩下的时间用 Facepalm... 有什么提示可以解决这个问题吗?或者是否有另一种方法来拦截 API 调用以执行另一个异步任务(无需在每个 API 方法中进行刷新检查......)
标签: ios block retain nsinvocation nsproxy