When and when not to use __block in Objective-C?

When using blocks, why do you need __block for some variables, and for other variables, such as function parameters, you do not?

+8
ios objective-c objective-c-blocks
source share
2 answers

The question is really worded incorrectly. This is not โ€œwhen do I need __block?โ€, It is โ€œwhat does __block do?โ€. Once you understand what he is doing, you can tell when you need it.

Usually, when a block captures a variable (capture occurs when the block refers to a variable outside of itself), it creates a copy of the variable (note that in the case of objects, a copy of the pointer is created, not the object itself), and if it is an object, it saves it.

This means that in normal behavior, you cannot use a block to change a value outside the block. This code is invalid, for example:

int x = 5; void(^block)() = ^{ x = 10; }; 

The __block qualifier makes two changes: most importantly, it tells the compiler that the block should capture it directly, and not make a copy. This means that you can update the value of variables outside the block. Less important, but still very important, when not using ARC, it tells the compiler not to save the captured objects.

+23
source share

The code block has access to any variables that are within the scope in which the block was declared. However, any variable / object declared outside the scope of the block is immutable inside the block. You can read it, but not change it. Setting the __block flag in an object declaration allows you to change it within the block area.

EDIT: Here's an example:

 NSString *myString = @"hello"; dispatch_sync(dispatch_get_main_queue(), ^{ myString = @"hello world"; }); 

This does not work and you will receive an error message.

 __block NSString *myString = @"hello"; dispatch_sync(dispatch_get_main_queue(), ^{ myString = @"hello world"; }); 

The problem is solved!

+14
source share

All Articles