本文介绍了将弱指针分配给强指针是否会复制对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

避免在区块内捕获自我的常见模式是在区块外创建弱自我,并使用它在区块(内部自我)内创建局部强"版本的自我.

The common pattern to avoid capturing self within a Block is to create a weak self outside the Block and use this to create a "locally strong" version of self within the Block (inner self).

__weak ClassX *weakSelf = self;
[someOtherObject methodThatTakesCOmpletionBlock: ^{

             ClassX innserSelf = weakSelf; //innserSelf creation?
             [someObject send:innerSelf.prop;}];

执行innserSelf creation行时会发生什么?方法methodThatTakesCompletionBlock:发送到someOtherObject时,innerSelf是自身的副本吗?

What happens when the innserSelf creation line is executed? Is innerSelf a copy of self at the time the method methodThatTakesCompletionBlock: is sent to someOtherObject?

这个问题只集中在执行innserSelf行时会发生什么.我已经看到在块内强烈引用弱引用相关,但没有解决这一点.

This question just focusses on what happens when the innserSelf line is executed. I've seen Strong reference to a weak references inside blocks which is related but doesn't address this point.

推荐答案

考虑:

 __weak id weakSelf = self;
 [other doSomething: ^{
     __strong id strongSelf = weakSelf;
     ....
 }];

other复制该块时,没有强引用.

When other copies the block, there is no strong reference.

other执行该块时,则在该块执行开始时创建强引用.完成该块后,执行范围消失了,因此strongSelf引用被破坏了.

When other executes the block, then the strong reference is created at the beginning of the block's execution. When the block is done, the execution scope is gone and, thus, the strongSelf reference is destroyed.

other是否挂在块上无关紧要; strongSelf引用仅在块执行期间存在.

Whether other hangs onto the block or not is irrelevant; the strongSelf reference only exists during block execution.

这篇关于将弱指针分配给强指针是否会复制对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:49