我在下面有一个与 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 变量声明为__block
类型并设置为 x 值。在块内,我已经为 cod 设置了 y 值,但在方法结束时,我得到了 cod 的 x 值。我尝试使用 cod = code 之类的东西然后返回 cod,尊重对象类型,但是我在块内分配的任何东西,我都无法获得它之外的值。我究竟做错了什么?