简体   繁体   English

在块中具有强引用的弱变量:不会创建保留周期吗?

[英]weak variable with a strong reference in a block: does not create a retain cycle?

why does it work when we pass the weak reference to a strong reference inside the block? 当我们将弱引用传递给块内部的强引用时,为什么它起作用? If a local variable in a block is retained, this should add a retain to self and thus create this bad retain cycle? 如果保留了块中的局部变量,是否应该向self添加一个保留,从而造成这个不良的保留周期?

Here is the example : 这是示例:

__weak id weakSelf = self; 
[self.operationQueue addOperationWithBlock:^{
    NSNumber* result = findLargestMersennePrime();
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 
        MyClass* strongSelf = weakSelf; 
        strongSelf.textLabel.text = [result stringValue];
    }]; 
}];

When you create or copy a block (it could be copied when you, for example, schedule it to gcd), referenced variables are captured (unless declared with __block specifier). 创建或复制一个块时(例如,在将其调度到gcd时可以复制它),将捕获引用的变量(除非使用__block指定符声明)。 Strong references are retained, weak references are not. 保留强引用,弱引用不保留。

When you create local strongSelf variable it keeps self alive while block executes (ie while it's not executed and sits in a property there's no strong reference). 当您创建局部strongSelf变量时,它会在执行块时使self保持活动状态(即,不执行且位于属性中的对象没有强引用)。 When you reference self directly - self is captured and retained, now it keeps self while block is alive . 当您引用self直接- self被捕获并保留下来,现在它保持self ,而块是活的

__weak id weakSelf = self; 
[self.operationQueue addOperationWithBlock:^{
    NSNumber* result = findLargestMersennePrime();
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 

        MyClass* strongSelf = weakSelf; // strong reference when block executes
        [self foo]; // strong reference when block created/copied

        strongSelf.textLabel.text = [result stringValue];
    }]; 
}];

See the difference? 看到不同? If you kill all strong pointers to object with direct self reference there is still one strong reference inside the block, the one which was captured and retained. 如果您使用直接self引用杀死所有指向对象的强指针,则在块内仍然存在一个强引用,该强引用被捕获并保留。 At the same time local strongSelf pointer only holds strong reference to self while block is executed, so, if self was already dead, weakSelf would be nil and strongSelf will get nil value. 同时,本地strongSelf指针仅在执行块时持有对self强引用,因此,如果self已死,则weakSelf将为nil, strongSelf将获得nil值。

no it doesn't create a cycle since self isn't captured as strong! 不,这不会产生循环,因为自我没有被捕捉为强者! :) :)

strongSelf is a strong reference that retains self BUT since strongSelf is a local var, it is released when the block is done and the retain count drops fine strongSelf是一个强引用,可保留self BUT,因为strongSelf是本地var,在完成块时释放它,并且保留计数下降

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM