在Objective-C中,如何将从块捕获的变量返回给调用者
我无法将块中捕获的异步响应/错误对返回给调用方。代码如下:在Objective-C中,如何将从块捕获的变量返回给调用者,objective-c,objective-c-blocks,Objective C,Objective C Blocks,我无法将块中捕获的异步响应/错误对返回给调用方。代码如下: - (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error { __block NSData* b_data = nil; __block NSURLResponse* b_response = nil; __block
- (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
{
__block NSData* b_data = nil;
__block NSURLResponse* b_response = nil;
__block NSError* b_error = nil;
dispatch_semaphore_t wait = dispatch_semaphore_create(0);
[self sendRequest:request completion:^(NSHTTPURLResponse* c_response, NSData* c_data, NSError* c_error) {
b_data = c_data;
b_response = c_response;
b_error = c_error;
dispatch_semaphore_signal(wait);
}];
dispatch_semaphore_wait(wait, DISPATCH_TIME_FOREVER);
response = &b_response; // ERROR: Assigning NSURLResponse *__strong * to NSURLResponse *__autoreleasing * changes retain/release properties of pointer
error = &b_error; // ERROR: Assigning NSError *__strong * to NSError *__autoreleasing * changes retain/release properties of pointer
return b_data;
}
基本上,我正在将异步请求转换为同步请求。我需要通过指针对指针将响应/错误对返回给调用方。然而,我遇到了一些关于弧和块的问题
我想将响应/错误从块中复制出来,并在不更改方法签名的情况下将其返回给调用者(有大量调用此方法的遗留代码-我正试图小心翼翼地用NSURLSession替换NSURLConnection)
是否有一种很好的方法可以提取结果并将其返回给调用者?您的两个错误与块无关。这些线路应为:
if (response) {
*response = b_response;
}
if (error) {
*error = b_error;
}
如果调用者通过参数的nil
,则需要if
检查。尝试取消对nil
指针的引用时将出现崩溃
也没有必要将响应/错误对复制到本地块变量。检查
nil
后,可以将它们直接写入参数 您的两个错误与块无关。这些线路应为:
if (response) {
*response = b_response;
}
if (error) {
*error = b_error;
}
如果调用者通过参数的nil
,则需要if
检查。尝试取消对nil
指针的引用时将出现崩溃
也没有必要将响应/错误对复制到本地块变量。检查
nil
后,可以将它们直接写入参数 哇。这是一个非常尴尬的指针错误。我将覆盖参数,而不是取消引用并写入结果。我将把这个作为一个例子,告诉大家不要做什么。这是一个非常尴尬的指针错误。我将覆盖参数,而不是取消引用并写入结果。我将把这个作为一个例子,说明什么是不应该做的。