Returning a variable value outside a block - Objective-C, iOS

不打扰是莪最后的温柔 提交于 2019-12-20 02:16:16

问题


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

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?


回答1:


Look at the method name:

[NSURLConnection sendAsynchronousRequest:...

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.



来源:https://stackoverflow.com/questions/15797721/returning-a-variable-value-outside-a-block-objective-c-ios

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!