我的代码低于使一个URL所涉及的连接,并获取像HTTP代码响应和最终URL有些报头的响应(用于重定向的情况下):返回一个变量值的块之外 - 的Objective-C,的iOS
- (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; }
正如所看到的,我已宣布鳕变量作为__block
类型和x值设定。 里面的块,我已经设置了鳕鱼的y值,但在方法结束时,我得到了鳕鱼的x值。 我试过使用类似cod = code的东西,然后返回鳕鱼,尊重对象类型,但是我在块内部分配的任何东西,我无法获得它之外的值。 我在做什么错?
备注:1.这与Xcode无关,它只是一个API和/或语言问题。 2.该语言称为Objective-C,不是客观的c,操作系统是iOS,而不是ios。 – 2013-04-03 20:51:25