What is the difference between a __weak and a __block reference?

Viewed 32076

I'm reading Xcode's documentation, and here is something that puzzles me:

__block typeof(self) tmpSelf = self;
[self methodThatTakesABlock:^ {
    [tmpSelf doSomething];
}];

The following is copied from the documentation:

A block forms a strong reference to variables it captures. If you use self within a block, the block forms a strong reference to self, so if self also has a strong reference to the block (which it typically does), a strong reference cycle results. To avoid the cycle, you need to create a weak (or __block) reference to self outside the block, as in the example above.

I don't understand what does 'a weak (or __block)' mean?

Is

__block typeof(self) tmpSelf = self;

and

__weak typeof(self) tmpSelf = self;

exactly the same here?

I found another piece in the document:

Note: In a garbage-collected environment, if you apply both __weak and __block modifiers to a variable, then the block will not ensure that it is kept alive.

So, I'm totally puzzled.

4 Answers

Beside other answers on __block vs __weak, there is another way to avoid retain cycle in your scenario.

@weakify(self);
[self methodThatTakesABlock:^ {
    @strongify(self);
    [self doSomething];
}];

More Info about @Weakify @Strongify Macro

When using self in block, should use __weak, not __block as it may retain self.

In case you need strong self, then you can use like this:

__weak typeof(self) *weakSelf = self;
[self methodThatTakesABlock:^{
    if (weakSelf) {
        __strong typeof(self) *strongSelf = weakSelf;
        [strongSelf doSomething];
    }
}];
Related