obj-c弱自我在一个块中:为什么第二个在两个相似的情况下不需要弱自我 [英] obj-c weak self in a block: why the 2nd one doesn't need a weak self inside in two similar cases
问题描述
我终于发现我的内存错误是由在一个块中强烈引用self引起的.但是我不知道为什么在类似情况下不需要弱点:
I finally found my memory bug is caused by referring self strongly in a block. But I don't know why in a similar case, the weak is not needed:
我有一个CameraCaptureManager类来执行图像捕获任务,而CameraViewController具有此管理器的强大属性.管理器的弱委托属性指向控制器.
I have a CameraCaptureManager class doing image capture tasks, and a CameraViewController has a strong property of this manager. The manager has weak delegate property pointing back to the controller.
这是我必须在管理器中使用weakSelf的地方,否则-(void)dealloc将不会被调用:
This is where I must use weakSelf in the manager, otherwise -(void)dealloc won't be called:
// 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:
The manager holds the deviceOrientationDidChangeObserver strongly, so weakSelf is needed to break the memory retain cycle. That's fine, I got that... but I find I don't have use weakSelf in a similar case in the same class:
[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来进行dealloc.我很困惑,请说明一下.
The manager also holds the stillImageOutput strongly, but why I can use the strong "self" in the completion block? The manager object gets dealloc with this strong self inside the block. I'm confused, please shed some light.
即使在第二种情况下也不会导致任何保留周期,我还需要使用weakSelf吗?
Also do I need to use weakSelf in the 2nd case even when it won't cause any retain cycle?
推荐答案
在第二个代码示例中,您有一个 temporary 保留周期.调用completionHandler
块后,将释放该块并与捕获的self
一起释放,因此
释放周期中断了.
In your second code example you have a temporary retain cycle. When the completionHandler
block has been called, the block is released and with it the captured self
, so
that the release cycle is broken.
这篇关于obj-c弱自我在一个块中:为什么第二个在两个相似的情况下不需要弱自我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!