我正在尝试适当地使用 NSURLConnection 的 sendAsynchronousRequest 方法,但我遇到了 block 参数的问题。我在调用上方构建了块,并使用 __block 变量尝试检索其中收集的数据。我已经确认块内的数据是正确的,所以块工作得很好,让块数据的检索成为问题。我在方法末尾的赋值和返回语句没有得到正确的值,我认为这是因为在赋值发生之前块尚未完成执行。如何在不中断主线程的情况下“等待”块完成执行后再执行分配?
- (NSData *) sendAsynchronousURLRequest: (NSMutableURLRequest *)request withResponse: (NSURLResponse *)response andError:(NSError *)error
{
// Prepare the block handler.
__block NSURLResponse *retrievedBlockResponse;
__block NSError *retrievedBlockError;
__block NSData *retrivedBlockData;
void(^requestHandler)(NSURLResponse*, NSData*, NSError*) =
^(NSURLResponse *blockResponse, NSData *blockData, NSError *blockError)
{
retrievedBlockResponse = blockResponse;
retrivedBlockData = blockData;
retrievedBlockError = blockError;
// NOTE: Correct data is here...
NSLog(@"Data Inside Block:\n%@", [NSMutableDictionary DictionaryFromJSONData:blockData errorReport:nil]);
};
// Send the asynchronous request (operationQueue initialized elsewhere in class).
[NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:requestHandler];
// NOTE: Reference to data cannot be established here!
// Establish references to block variables and return NSData object.
response = retrievedBlockResponse;
error = retrievedBlockError;
return retrivedBlockData;
}