blocks, self, retain cycles

前端 未结 1 1307
再見小時候
再見小時候 2021-02-03 15:06

I\'m having a bit of trouble getting my head around referencing self within a block, and not creating a retain cycle.

Can you let me know if my understanding is correct:

相关标签:
1条回答
  • 2021-02-03 15:53

    Yes, that is correct, with a few exceptions:

    A retain cycle only happens if self ends up retaining the block indirectly, e.g. setting property myblock on property of self myproperty:

    self.myproperty.myblock = ^{ [self dosomething]; }; // ERROR: Retain Cycle
    

    However, a retain cycle doesn't (usually) happen when using blocks for something like dispatch code, like this:

    dispatch_async(dispatch_get_main_queue(), ^{ [self dosomething]; }); // Safe, dispatch_async will not be retained by you
    

    Unless of course you call that dispatch_async function inside a block that has the criteria for being a retain cycle.

    It is really confusing, and it's something I hope gets fixed. Now, for my own opinion:


    It wasn't always the case, in pre-ARC code this wasn't an issue, but since blocks now automatically retain any objects they capture, it's an issue.

    I wish this would get fixed, as it'd be a quite easy fix, by having self's type be a __weak instancetype const instead of a instancetype const. It would also solve some issues with creating class clusters in ARC, which admittedly isn't the largest of issues, but it still exists.

    As far as advantages to retain cycles, there are not many.

    0 讨论(0)
提交回复
热议问题