问题
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);
回答1:
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
回答2:
You don't. Well, you can just access it like you are. But the purpose of the block is that it will be called asynchronously after some delay when the information is actually available so you should do your processing in the block or call another method from the block to do it.
回答3:
The code in the block is run asynchronously. So the code after the block is run before the code in the block has had a chance to run (or certainly complete at least).
see this tutorial on developer.apple.com Working with Blocks
来源:https://stackoverflow.com/questions/17572202/how-can-i-access-a-block-variable-after-the-block-has-completed