Search code examples
iosobjective-cobjective-c-blocksretain-cycle

RetainCycle with Globals


Let's say in iOS we have:

In W2AppDelegate.m:

GlobalViewController *globalVc;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
...

}

In SomeOtherViewController.m:

- (void)viewDidLoad {
    [super viewDidLoad];

    [globalVc doSomething^{
       [globalVc.someVariable doSomethingElse]; // Is there a retain cycle here?
    }];
}

Is there a retain cycle here since we have a strong reference to globalVc inside the block.

globalVc -> block -> globalVc


Solution

  • Is there a retain cycle here since we have a strong reference to globalVc inside the block.

    No. Because Blocks capture local variables only.

    [globalVc doSomething^{
       [globalVc.someVariable doSomethingElse]; // Is there a retain cycle here?
    }];
    

    globalVc wasn't captured by the block because globalVc is global variable. No local variables here, So the block doesn't capture any objects, Thus the block doesn't retain any objects at all.