OBJ-C 块中的弱自我:为什么在两个类似情况下,第二个不需要弱自我



我终于发现我的内存错误是由在块中强引用self引起的。但我不知道为什么在类似的情况下,不需要弱者:

我有一个CameraCaptureManager类来执行图像捕获任务,而CameraViewController具有该管理器的强大属性。管理器具有指向控制器的弱委托属性。

这是我必须在管理器中使用weakSelf的地方,否则将不会调用-(void)dealloc:

    // in CameraCaptureManager
    __weak CameraCaptureManager *weakSelf = self;
    void (^deviceOrientationDidChangeBlock)(NSNotification *) = ^(NSNotification *notification) {
        UIDeviceOrientation deviceOrientation = [[UIDevice currentDevice] orientation];
        [weakSelf updateVideoOrientation:deviceOrientation];
    };
    self.deviceOrientationDidChangeObserver = [notificationCenter addObserverForName:UIDeviceOrientationDidChangeNotification
                                                                              object:nil
                                                                               queue:nil
                                                                          usingBlock:deviceOrientationDidChangeBlock];  

管理器强烈持有deviceOrientationDidChangeObserver,因此需要weakSelf来打破内存保留周期。没关系,我明白了。。。但我发现我没有在同一类中的类似情况下使用weakSelf:

[self.stillImageOutput captureStillImageAsynchronouslyFromConnection:captureConnection
                                                   completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error){
                                                       UIImage *image = nil;
                                                       if (imageDataSampleBuffer != NULL) {
                                                           NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer]; 
                                                           image = [[UIImage alloc] initWithData:imageData];
                                                       } 
                                                       if ([self.delegate respondsToSelector:@selector(captureManager:capturedStillImage:)]) {
                                                           [self.delegate captureManager:weakSelf capturedStillImage:image];
                                                       }
                                                   }]; 

经理也强烈地持有stillImageOutput,但为什么我可以在完成块中使用强烈的"self"?管理器对象在块内与这个强self解除锁定。我很困惑,请澄清一下。

此外,在第二种情况下,我是否需要使用weakSelf,即使它不会引起任何保留循环?

在第二个代码示例中,您有一个临时保留周期。当调用了completionHandler块时,该块被释放,并随之释放捕获的self,因此释放周期被打破。

最新更新