开发者

How is the "__block" keyword in Objective-c used?

开发者 https://www.devze.com 2023-04-03 02:12 出处:网络
Just noticed the __block keyword 开发者_Go百科in some Objective-c code like the following: // myString passed into the method

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:

  1. It allows the variable to be assigned to inside a block that captures it.
  2. It allows the block to see changes to the value of the variable after the block was created.
  3. Under MRC, a __block variable of object pointer type is not retained by the block when the block is copied.
0

精彩评论

暂无评论...
验证码 换一张
取 消