iWenPro
iWenPro

Reputation: 49

what does __block mean in Apple doc sample code?

When read NotificationCenter document, I found the sample code below. What I want to clarify is what does __block mean here? I know when using __block variable can change in block, but token doesn't changed.

    NSNotificationCenter * __weak center = [NSNotificationCenter defaultCenter];
    id __block token = [center addObserverForName:@"OneTimeNotification"
                                           object:nil
                                            queue:[NSOperationQueue mainQueue]
                                       usingBlock:^(NSNotification *note) {
                                           NSLog(@"Received the notification!");
                                           [center removeObserver:token];
                                       }];

Upvotes: 2

Views: 41

Answers (2)

newacct
newacct

Reputation: 122518

I know when using __block variable can change in block, but token doesn't changed.

__block shares the variable between all the blocks that capture it, as well as the outside scope where it is declared. It is not only useful when you need to modify the variable inside the block, but also when you modify the variable outside the block and want the changes to be visible in the block.

That is what is happening here. The entire right side of the =, including the creation of the lambda and the method call, happen first, and then afterwards the result is assigned to the token variable. token is captured by the lambda when the lambda is created, which happens before you assign to token. So if the lambda just captures the value of token, it will always have the value of token at the point it captured it (before the assignment), which is nil.

token is assigned a value in the outside scope after token is captured by the lambda. In order for the lambda to see this new value of token, the variable must be shared between the scopes, with __block.

Upvotes: 0

Asperi
Asperi

Reputation: 258461

It allows to use token within block of initialization construction, indicating that its value will be changed later, so can be used in block.

Otherwise you get as below.

demo

Upvotes: 2

Related Questions