简体   繁体   中英

Why does Xcode complain sometimes and not always when self is used inside a block?

Suppose the following situation:

  self.collectionViewController.didEndDisplayingCell = ^(CollectionViewCell *cell) {
    [self doSomething];    
  };

Xcode will complain that I cannot use self inside that method or I will have a retain cycle.

Then another situation. I create a class that loads an image and runs something on completion and call it like

[[MyImageClass sharedInstance] loadImageFromUrl:url
                             runOnCompletion:^(UIImage *image) {
                               [self doSomething];
                             }];

Xcode will not complain in that case and self is used inside a block!

why?

The first case:

The self object keep strong reference to block object.

Vice versa, block of also retain self object. Since blocks capture their context, package it up, and carry it along for the ride, any reference to self (or implicit reference with an ivar) within a block also will capture a strong reference to self . You can refer this https://blackpixel.com/writing/2014/03/capturing-myself.html

So, it will be retain cycle !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM