在块完成后如何访问 __block 变量? [英] How can I access a __block variable, after the block has completed?
问题描述
我正在使用 Parse.com 进行一些后台操作,但这是关于 __block
变量的一般问题.我想定义一个变量,使用完成块运行后台网络操作,可能在块内修改该变量,然后在块外访问它.但它始终为零.
I'm doing some background operations with Parse.com, but this is a general question about __block
variables. I want to define a variable, run a background network operation with a completion block, possibly modify that variable within the block, then access it outside of the block. But it's always nil.
如何将变量保留在块之外?这是在类方法中,因此不能选择使用实例变量.
How can I retain the variable outside of the block? This is inside a class method, so using an instance variable isn't an option.
__block PFObject *myObject = nil;
PFQuery *query = [PFQuery queryWithClassName:@"ClassName"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (objects.count) {
myObject = [objects lastObject];
}
}];
NSLog(@"%@",myObject);
推荐答案
您可以在块外使用它们,就像任何其他变量一样.
You can use them outside block just like any other variable.
在您当前的代码中,此日志将打印 nil,因为块内的代码是异步执行的,在这种情况下 - 当搜索结果返回时.
In your current code this log will print nil, because code inside the block gets executed asynchronously, in this case - when the search results return.
如果你想从 myObject
获得有意义的值,你应该在 myObject
赋值之后把你的日志放在块中.
If you want meaningful value from myObject
, you should really put your log inside the block, after myObject
assignment.
在评论中查看执行顺序:
See the order of execution in comments:
__block PFObject *myObject = nil; //1
PFQuery *query = [PFQuery queryWithClassName:@"ClassName"]; //2
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { //3
if (objects.count) //5
myObject = [objects lastObject]; //6
}]; //7
NSLog(@"%@",myObject); //4
这篇关于在块完成后如何访问 __block 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!