I was always using __weak
references to self
when I was in a block in GCD
. Everyone recommends that. I know that strong reference to self
(tested) in GCD can't produce retain cycles.
Apple recommends using a __weak
reference to self and then a __strong
reference to that _week
reference to guarantee that self
won't be nil
when the block is executed.
I have the following piece of code:
- (IBAction)startGCD:(id)sender {
GCDVC* __weak weakSelf = self;
[self.activityIndicator startAnimating];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ // 1
// VC2* __strong strongSelf = weakSelf;
[weakSelf.proArray addObject:@"2"];
[NSThread sleepForTimeInterval:10];
NSLog(@"%@",weakSelf.proArray);
dispatch_async(dispatch_get_main_queue(), ^{ // 2
[weakSelf.activityIndicator stopAnimating];
});
});
}
Test 1 I press the button and the Indicator is spinning. I press the back button before the GCD finish and the GCDViewController is being released.
Test 2 Then I uncomment the strong reference to self and I execute the same procedure. The GCDViewController is not released until the block has finished it work. But then its released.
Test 3
Now if I refer directly to self (without __weak
or __strong
) I have the exact behaviour with Test 2.
So if I want to make sure that the self won't be nil when the block is executed what's the point of using a __strong
reference to a __weak
reference to self
? Do I miss something here? Is any example that would change the result of Test 2 & 3?