Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

block

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?

like image 320
thiagomorales Avatar asked Feb 28 '26 00:02

thiagomorales


1 Answers

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.