本文介绍了块完成后如何访问__block变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 03:42