在块外返回变量值-Objective-C,iOS [英] Returning a variable value outside a block - Objective-C, iOS

查看:84
本文介绍了在块外返回变量值-Objective-C,iOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面的代码中有一个到URL的连接,并获取了一些标头响应,例如http代码响应和最终URL(用于重定向的情况):

I have the code below that a an connection to an URL and fetches some header responses like http code response and final URL (for redirection case):


- (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值. 在块内部,我用y值设置了cod,但是在方法结束时我得到了cod的x值. 我试图使用类似cod = code的方法,然后返回cod,尊重对象类型,但是我在block内分配的任何内容,我都无法获得它之外的值. 我在做什么错了?

As can see, I have declared cod variable as __block type and set with x value. Inside block, I've set cod with y value, but at end of method I got x value for cod. I've tried to use something like cod = code then returns cod, respecting objects type, but anything that I assign inside block, I can't get the value outside it. What am I doing wrong?

推荐答案

查看方法名称:

[NSURLConnection sendAsynchronousRequest:...

哇!所以它是异步的.到完成块被调用时,您的test方法将已经返回.您无法从同步方法返回异步调用的结果,因为它没有意义.使您的类适应网络操作的异步特性,使用回调,委托等.总而言之,重新设计代码.

Whoops! So it's asynchronous. By the time the completion block is called, your test method will have already returned. You can't return the result of an asynchronous call from a synchronous method, because it doesn't make sense. Adapt your class to be coherent with the async nature of networking operations, use callbacks, delegation, etc. All in all, redesign your code.

这篇关于在块外返回变量值-Objective-C,iOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆