Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C Blocks and variable scope

I would like to set the value of an NSData object within my block. Can someone let me know what I have done wrong here?

// Data
__block NSData *data = nil;

[ZSURLConnection performRequestWithUrl:wsdlURL xmlString:xml completionHandler:^(NSData *response, NSError *error) {

    // Handle the error
    if (error) {
        NSLog(@"Error: %@", [error localizedDescription]);
    } else {
        data = response;
    }//end

}];//end block

if (data) {
    NSString *d = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    NSLog(@"DATA --- %@", d);
}

return data;

Why can't I assign the response to data and then retrieve it outside of my block?

like image 257
Nic Hubbard Avatar asked Dec 06 '25 02:12

Nic Hubbard


1 Answers

Because the block runs asynchronously, after the rest of your method. Either rewrite your calling code to work with the asynchronous loading, or find a way to perform the block's work synchronously. I don't know what ZSURLConnection is, but check to see if it has a version of the "perform..." method that doesn't run in the background.

like image 70
Jonathan Grynspan Avatar answered Dec 07 '25 18:12

Jonathan Grynspan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!