I'm getting an error
Variable is not assignable (missing __block type specifier)
on the line aPerson = participant;
. How can I make sure the block can access the aPerson
variable and the aPerson
variable can be returned?
Person *aPerson = nil; [participants enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { Person *participant = (Person*)obj; if ([participant.gender isEqualToString:@"M"]) { aPerson = participant; *stop = YES; } }]; return aPerson;
You can declare local variables anywhere in a method body. However, if you declare a variable within a block, then it only has scope within the block. We started a block and within the block we declared y. y is created at the declaration.
To access a variable outside a function in JavaScript make your variable accessible from outside the function. First, declare it outside the function, then use it inside the function. You can't access variables declared inside a function from outside a function.
You use blocks to limit the scope of a variable. The main reason of a block is that x is not accessible outside the block. If you want to access a variable outside a bock, declare it outside the block.
Local variables cannot be accessed outside the function declaration. Global variable and local variable can have same name without affecting each other. JavaScript does not allow block level scope inside { } brackets.
You need to use this line of code to resolve your problem:
__block Person *aPerson = nil;
For more details, please refer to this tutorial: Blocks and Variables
Just a reminder of a mistake I made myself too, the
__block
declaration must be done when first declaring the variable, that is, OUTSIDE of the block, not inside of it. This should resolve problems mentioned in the comments about the variable not retaining its value outside of the block.
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