Retain loop in a block

337 views Asked by At

I'm trying to get variables and properties in self in a block for actions to complete, but, if I reference self or a global variable in self when self is the object running the block, it warns me of a retain loop. Here's what I'm doing:

  • I'm adding actions to an NSMutableArray that are of type (void(^)() (in other words, a block returning void with no parameters).
  • I call it using this syntax later on, where i is an int determined by code (that is in the bounds of the array:

    void (^someBlock)() = arrayOfActions[i]; someBlock();

The code works and runs fine, but, because I use properties of self within the block, Xcode warns me of a retain loop. Should I ignore it because it's simply a warning and everything works fine in code (it only executes the block once), or should I do something different?

1

There are 1 answers

0
uraimo On BEST ANSWER

You should definitely not ignore the warning, but use __weak instead to define a weak reference and eliminate retain cycles as described in the documentation:

__weak SelfType *weakSelf = self;

void (^aBlock)() = ^(){
    SelfType *strongSelf = weakSelf;
    //User strongSelf
};

Alternatively you can use libextobjc (https://github.com/jspahrsummers/libextobjc) with its convenient @strongify and @weakify annotations.