Does assigning a weak pointer to a strong pointer copy the object?

自作多情 提交于 2019-12-12 03:45:20

问题


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;}];

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?

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.


回答1:


Consider:

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

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

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.

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




回答2:


Assigning a weak pointer to a strong one does not copy the object. Both pointers will point to the same object. The strong pointer retains thus adding +1 to the retain count. The weak pointer does not alter the retain count



来源:https://stackoverflow.com/questions/39938439/does-assigning-a-weak-pointer-to-a-strong-pointer-copy-the-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!