下面的代码是一个与URL的连接,并获取一些标头响应,如http代码响应和最终URL(用于重定向的情况):
- (NSString *)test
{
__block NSString *cod = @"x";
NSString *urlString = @"http://www.google.com";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:15.0f];
[request setHTTPMethod:@"HEAD"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
NSURL *resolvedURL = [httpResponse URL];
NSString *code = [NSString stringWithFormat:@"%ld", (long)[httpResponse statusCode]];
NSLog(@"%@", resolvedURL);
NSLog(@"%@", code);
cod = @"y"; // the idea was use something like 'cod = code', then return 'code' at end.. But it dont works too.
}];
return cod; }
可以看出,我已将cod变量声明为[request setHTTPMethod:@"HEAD"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
NSURL *resolvedURL = [httpResponse URL];
NSString *code = [NSString stringWithFormat:@"%ld", (long)[httpResponse statusCode]];
NSLog(@"%@", resolvedURL);
NSLog(@"%@", code);
cod = @"y"; // the idea was use something like 'cod = code', then return 'code' at end.. But it dont works too.
}];
return cod; }
类型并设置为x值。
在内部块中,我将cod设置为y值,但在方法结束时,我得到了鳕鱼的x值。
我试图使用像cod = code然后返回cod,尊重对象类型,但我在块内分配的任何东西,我都无法获得它之外的值。
我做错了什么?
答案 0 :(得分:4)
查看方法名称:
[NSURLConnection sendAsynchronousRequest:...
糟糕!所以它是异步的。调用完成块时,您的test
方法已经返回。您无法从同步方法返回异步调用的结果,因为它没有意义。使您的课程与网络操作的异步性质保持一致,使用回调,委托等等。总而言之,重新设计您的代码。