Why need weak self in block?

305 Views Asked by At

Just like the following code:

__weak typeof(self) weakSelf = self;
[self methodThatTakesABlock:^ {
    [weakSelf doSomething];
    //[self doSomething];//Why not this line?
}];
1

There are 1 best solutions below

1
On
[self methodThatTakesABlock:^ {
    [self doSomething];
}];

Does not cause a retain cycle unless the completion block is stored within self. If it is a property then, self will have a strong reference to the block and the block will have a strong reference to self causing a retain cycle. That is why you need to use weak, to avoid this retain cycle. But remember, you must use a weak self only within blocks that are stored as properties or ivars within self.

If the completion block is only called in the methodThatTakesABlock then you don't have to use a weak self since the block is not retained. In this case, the block will have a strong reference to self but self will not have one towards the block, so no retain cycle in this case.