404

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;
John Topley
  • 113,588
  • 46
  • 195
  • 237
tommi
  • 6,883
  • 8
  • 37
  • 60

8 Answers8

823

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
Devarshi
  • 16,440
  • 13
  • 72
  • 125
43

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.

Denis Balko
  • 1,566
  • 2
  • 15
  • 30
19

Just use the __block prefix to declare and assign any type of variable inside a block.

For example:

__block Person *aPerson = nil;

__block NSString *name = nil;
Luke
  • 11,426
  • 43
  • 60
  • 69
Umesh Sawant
  • 329
  • 2
  • 6
11

To assign a variable inside block which outside of block always use __block specifier before that variable your code should be like this:-

__block Person *aPerson = nil;
Luke
  • 11,426
  • 43
  • 60
  • 69
Gaurav
  • 553
  • 5
  • 9
10
__block Person *aPerson = nil;
Luke
  • 11,426
  • 43
  • 60
  • 69
Ketan Patel
  • 550
  • 4
  • 11
3

Try __weak if you get any warning regarding retain cycle else use __block

Person *strongPerson = [Person new];
__weak Person *weakPerson = person;

Now you can refer weakPerson object inside block.

PradeepKN
  • 617
  • 7
  • 10
3

yes block are the most used functionality , so in order to avoid the retain cycle we should avoid using the strong variable,including self inside the block, inspite use the _weak or weakself.

3

When I saw the same error, I tried to resolve it like:

   __block CGFloat docHeight = 0.0;


    [self evaluateJavaScript:@"document.height" completionHandler:^(id height, NSError *error) {
        //height
        NSLog(@"=========>document.height:@%@",height);
        docHeight = [height floatValue];
    }];

and its working fine

Just add "__block" before Variable.

Mr.Javed Multani
  • 12,549
  • 4
  • 53
  • 52