Reputation: 19757
Just noticed the __block
keyword in some Objective-c code like the following:
// myString passed into the method
__block NSString *_myString = myString;
How does the __block
keyword change the behavior of the above code?
Upvotes: 2
Views: 1435
Reputation: 122518
It allows several things:
__block
variable of object pointer type is not retained by the block when the block is copied.Upvotes: 0
Reputation: 199
With only the statement above the __block modifier won't do anything. In the context of a block however, the __block allows blocks defined in this method to mutate the variable.
__block NSString *myString = @"My string";
NSLog(@"myString: %@", myString);
dispatch_async(dispatch_get_main_queue(), ^{
myString = @"My string changed.";
});
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"myString: %@", myString);
});
In this example, the blocks can change myString to point to a new variable. It's analagous to passing the variable by reference. If I remove the __block modifier from the declaration of myString I would get a compilation stating, "Variable is not assignable (missing __block type specifier).
Upvotes: 0
Reputation: 49354
This variable modifier gives the ability for the variable to be modified in block's scope.
Upvotes: 6