Do I need to use a weak self pointer if a method called from a Block uses self?

后端 未结 4 784
悲&欢浪女
悲&欢浪女 2021-01-15 14:46

Using self. in blocks causes retain cycles, so I need to create a reference to weakSelf. I understand this

BUT!

If from my block I

4条回答
  •  灰色年华
    2021-01-15 15:35

    You don't need to worry about references while the block is executing - eventually it finishes doing whatever it does, and all these references go away.

    What you need to worry about are the references that are captured when the block is created. These references stay until the block goes away. So if your block has a reference to "self", that reference is there just because the block exists. And if you store that block in a property of self, you have a cycle.

    So if you store a block as a property in self, then the block shouldn't capture self. That's easily done by letting it access and capture a weak copy of self. Remember that when the block is executing, the weak copy of self may be nil. Which means the self object has already left our world, and your block might not need to do anything.

提交回复
热议问题