我正在尝试正确使用NSURLConnection的sendAsynchronousRequest方法,但我遇到了阻塞参数问题。我在调用之上构建了块,并使用__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;
}