Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
985 views
in Technique[技术] by (71.8m points)

ios - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...