0

I am trying to learn AVFoundation sample code "AVCam". In the sample code project, AVCamViewController.m class, there is an implementation like

__weak AVCamViewController *weakSelf = self;
[self setRuntimeErrorHandlingObserver:[[NSNotificationCenter defaultCenter] addObserverForName:AVCaptureSessionRuntimeErrorNotification
                                                                                            object:[self session]
                                                                                             queue:nil
                                                                                        usingBlock:^(NSNotification *note) {
AVCamViewController *strongSelf = weakSelf;

My question is why we want to first declare a __weak pointer, and later on assign this weak pointer to *strongSelf. What would be the difference that if we assign "self" directly
Something like:

AVCamViewController *strongSelf = self

Whole code https://developer.apple.com/library/prerelease/ios/samplecode/AVCam/Listings/AVCam_AVCamViewController_m.html

user454083
  • 1,337
  • 3
  • 16
  • 31

2 Answers2

1

If we pass self it could lead to a retain cycle under certain conditions (For example some object may have strong reference to the block and self might have strong reference to that object). Passing weak reference into the block guarantees absence of such a retain cycle. But we still may need to keep self alive while block is executed. That's why we assign weak reference to a strong one.

Conclusion: passing weak reference into a block and assinging it to a strong reference retains object for the time of block execution and at the same time it guarantees that no retain cycles will be made

Andrey Chernukha
  • 21,488
  • 17
  • 97
  • 161
1

The purpose of weakSelf is to ensure that the notification center observer doesn't maintain a strong reference to AVCamViewController. The presence of strongSelf inside the block is to avoid race conditions where AVCamViewController might be deallocated in the middle of a notification (thus if weakSelf existed when the notification came in, keep it around for the duration of the processing of the notification; but if weakSelf didn't exist when the notification came in, then strongSelf would be nil, too).

This process (sometimes joking called the "weak self-strong self dance") is critical. If you just have strongSelf = self, you've reintroduced the strong reference cycle (previously known as "retain cycle") that the above pattern worked so hard to resolve.

Rob
  • 415,655
  • 72
  • 787
  • 1,044