Question about __weak pointers (week 4, module 10)

In the video on ‘Blocks and Callbacks’ (week 4, module 10) at about 30:20 (min:sec) of the video execution time it is mentioned that in order to break the reference cycle you use the following code:

__weak id weakSelf = self;
void (^myBlock)() = ^{
    id strongSelf = weakSelf;
    if(!strongSelf) return;

NSLog ("This is my new data %@\n", strongSelf.req);
}

I don’t understand why do we need to create a strongSelf pointer inside the block. Why couldn’t we use the following:

__weak id weakSelf = self;
void (^myBlock)() = ^{
   if(!weakSelf) return;

NSLog ("This is my new data %@\n", weakSelf.req);
}

Thanks in advance.

It’s a corner case (or more formally a “race-condition”), but it’s possible that after you run
if(!weakSelf) return;
but before you end the block, the garbage collector could eliminate the weakSelf reference.
If it did that and you tried to use weakSelf you would get unexpected data because it would be reused by some other code.
By anchoring it to a strongSelf reference you are sure you have access to it for the remainder of the block’s execution.

1 Like

Thank you! It’s clear now.