Referring to weak self inside a nested block

前端 未结 2 393
一整个雨季
一整个雨季 2020-12-01 03:00

Suppose I already create a weak self using

__weak typeof(self) weakSelf = self;
[self doABlockOperation:^{
        ...
}];

Inside that bloc

2条回答
  •  余生分开走
    2020-12-01 03:12

    Your code will work fine: the weak reference will not cause a retain cycle as you explicitly instruct ARC not to increase the retainCount of your weak object. For best practice, however, you should create a strong reference of your object using the weak one. This won't create a retain cycle either as the strong pointer within the block will only exist until the block completes (it's only scope is the block itself).

    __weak typeof(self) weakSelf = self;
    [self doABlockOperation:^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (strongSelf) {
            ...
        }
    }];
    

提交回复
热议问题