Objective-C块和变量范围 [英] Objective-C Blocks and variable scope

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

问题描述

我想在我的块中设置一个 NSData 对象的值。有人可以让我知道我在这里做错了什么?

  // Data 
__block NSData * data = nil;

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

//处理错误
if {
NSLog(@Error:%@,[error localizedDescription]);
} else {
data = response;
} // end

}]; // end block

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

返回数据;

为什么无法将响应分配给数据

因为这个区块是非同步执行的,你的方法的其余部分。重写你的调用代码以处理异步加载,或者找到一种方法来同步执行块的工作。我不知道 ZSURLConnection 是什么,但检查它是否有一个版本的执行...方法不在后台运行。 / p>

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?

解决方案

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.

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

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