Avoiding the “capturing self strongly in this block is likely to lead to a retain cycle” message

后端 未结 3 969
情书的邮戳
情书的邮戳 2021-02-03 11:00

every time I have to use a global var or property inside a block like this:

self.save = ^(){
  if (isItSaving == NO) {
      [self saveMyFile];
  }
};

3条回答
  •  终归单人心
    2021-02-03 11:36

    The problem only occurs when referencing self from within the block, explicitly or implicitly. There's no warning emitted when accessing global variables.

    In your case you probably accessed a (boolean) ivar. Accessing the ivar implicitly uses self, that's why the compiler is warning you (correctly) about a retain cycle.

    The common way to fix the retain cycle is:

    typeof(self) __weak weakSelf = self;
    
    self.save = ^() {
        typeof(weakSelf) __strong strongSelf = weakSelf;
        if (strongSelf != nil && ! strongSelf->isItSaving) {
            [strongSelf saveMyFile];
        }
    };
    

    ... and, yes, that's a bit of an ugly part of blocks.

提交回复
热议问题