Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access a __block variable, after the block has completed? [duplicate]

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);
like image 653
James White Avatar asked Dec 07 '22 06:12

James White


1 Answers

You can use them outside block just like any other variable.

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.

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
like image 56
Nirav Bhatt Avatar answered Dec 10 '22 12:12

Nirav Bhatt