Just noticed the __block
keyword 开发者_Go百科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?
This variable modifier gives the ability for the variable to be modified in block's scope.
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).
It allows several things:
- It allows the variable to be assigned to inside a block that captures it.
- It allows the block to see changes to the value of the variable after the block was created.
- Under MRC, a
__block
variable of object pointer type is not retained by the block when the block is copied.
精彩评论