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

391

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;

This question is tagged with objective-c compiler-errors objective-c-blocks

~ Asked on 2011-11-01 05:16:56

The Best Answer is


794

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

~ Answered on 2011-11-01 05:31:25


41

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.

~ Answered on 2014-03-02 23:57:14


Most Viewed Questions: