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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With