[objective-c] 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;

This question is related to objective-c compiler-errors objective-c-blocks

The answer is


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.


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;

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;

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.


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.


__block Person *aPerson = nil;

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.


Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to compiler-errors

intellij idea - Error: java: invalid source release 1.9 Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug' Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error Android java.exe finished with non-zero exit value 1 error: expected primary-expression before ')' token (C) What does "collect2: error: ld returned 1 exit status" mean? Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing Maven error :Perhaps you are running on a JRE rather than a JDK? What does a "Cannot find symbol" or "Cannot resolve symbol" error mean? Operator overloading ==, !=, Equals

Examples related to objective-c-blocks

Store a closure as a variable in Swift Waiting until two async blocks are executed before starting another block Assign a variable inside a Block to a variable outside a Block What does the "__block" keyword mean? How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:? Can I use Objective-C blocks as properties?