我试图将block参数传递给
更新:我将代码更新如下。这些块是
区块会按照以下方式在链中传递:
NSInvocation → NSProxy(使用forwardInvocation的NSInvocation)→ method1 → methodN
methodN最终根据HTTP响应调用成功或失败的block。
我需要在每个阶段都复制该块吗? 上面的示例是关于第一个NSInvocation的。 我还需要在每个适当的步骤上使用[invocation retainArguments]; 吗? 我正在使用ARC。
NSInvocation
,但是应用程序崩溃了。该调用发出网络请求并调用成功或失败的块。我认为问题在于块在网络请求完成之前被释放了。我设法通过一些Block_copy
技巧使其正常工作,并且使用Instruments没有报告任何泄漏。
问题: - 即使Static Analyzer或Instruments没有报告,是否可能存在泄漏? - 有更好的“保留”块的方法吗?
// Create the NSInvocation
NSMethodSignature *methodSignature = [target methodSignatureForSelector:selector];
NSInvocation* invoc = [NSInvocation invocationWithMethodSignature:methodSignature];
[invoc setTarget:target];
[invoc setSelector:selector];
// Create success and error blocks.
void (^successBlock)(id successResponse) = ^(id successResponse) {
// Some success code here ...
};
void (^errorBlock)(NSError *error) = ^(NSError *error) {
// Some failure code here ...
};
/*
Without the two Block_copy lines, the block gets dealloced too soon
and the app crashes with EXC_BAD_ACCESS
I tried [successBlock copy] and [failureBlock copy] instead,
but the app still crashes.
It seems like Block_copy is the only way to move the block to the heap in this case.
*/
Block_copy((__bridge void *)successBlock);
Block_copy((__bridge void *)errorBlock);
// Set the success and failure blocks.
[invoc setArgument:&successBlock atIndex:2];
[invoc setArgument:&errorBlock atIndex:3];
[invoc retainArguments]; // does not retain blocks
// Invoke the method.
[invoc invoke];
更新:我将代码更新如下。这些块是
NSMallocBlocks
,但应用程序仍然崩溃。// Create success and error blocks.
int i = 0;
void (^successBlock)(id successResponse) = ^(id successResponse) {
NSLog(@"i = %i", i);
// Some success code here ...
};
void (^errorBlock)(NSError *error) = ^(NSError *error) {
NSLog(@"i = %i", i);
// Some failure code here ...
};
/*** Both blocks are NSMallocBlocks here ***/
// Set the success and failure blocks.
void (^successBlockCopy)(id successResponse) = [successBlock copy];
void (^errorBlockCopy)(NSError *error) = [errorBlock copy];
/*** Both blocks are still NSMallocBlocks here - I think copy is a NoOp ***/
// Set the success and failure blocks.
[invoc setArgument:&successBlockCopy atIndex:2];
[invoc setArgument:&errorBlockCopy atIndex:3];
[invoc retainArguments]; // does not retain blocks
// Invoke the method.
[invoc invoke];
区块会按照以下方式在链中传递:
NSInvocation → NSProxy(使用forwardInvocation的NSInvocation)→ method1 → methodN
methodN最终根据HTTP响应调用成功或失败的block。
我需要在每个阶段都复制该块吗? 上面的示例是关于第一个NSInvocation的。 我还需要在每个适当的步骤上使用[invocation retainArguments]; 吗? 我正在使用ARC。