Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a variable inside a Block to a variable outside a Block

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; 
like image 301
tommi Avatar asked Nov 01 '11 05:11

tommi


People also ask

When you declare a variable within a block it is local to that block?

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.

How do you use the inside function variable in an outside function?

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.

How do you use a variable from outside the block in JavaScript?

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.

Can we access local variable 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.


2 Answers

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

like image 176
Devarshi Avatar answered Oct 14 '22 17:10

Devarshi


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.

like image 27
Denis Balko Avatar answered Oct 14 '22 16:10

Denis Balko