在块外返回一个variables值 – Objective-C,iOS

我有下面的代码,连接到一个URL,并获取一些头响应,如http代码响应和最终的URL(redirect的情况下):

- (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; } 

可以看到,我已经将codvariables声明为__blocktypes,并用x值进行设置。 在块内部,我已经设置了鳕鱼的y值,但是在方法结束时,我得到了鳕鱼的x值。 我尝试过使用类似于cod = code的东西,然后返回cod,尊重对象的types,但是我在块内部分配的任何东西,我无法获得它之外的值。 我究竟做错了什么?

看方法名称:

 [NSURLConnection sendAsynchronousRequest:... 

哎呦! 所以它是asynchronous的。 在完成块被调用的时候,你的test方法已经返回了。 您不能从同步方法返回asynchronous调用的结果,因为它没有任何意义。 调整你的class级与networking操作的asynchronous性质相一致,使用callback,委托等。总而言之,重新devise你的代码。