Retain cycle concern

Neru

I took over project from another company and I often see this part of code when assigning value to variable:

// interface:
@property NSArray *foos;


// somewhere in implementation:
BOOL foosExist = ^BOOL {
    return self.foos.count > 0; // self inside block
}();

Moreover compiler claims when referencing inside block to foos property by underlying variable _foos:

Block implicitly retains "self"; explicitly mention "self" to indicate this is intended behavior.

Does this self inside block truly creates retain cycle? If not, why? Can someone elaborate?

CRD

There is no cycle in your example.

Your block is simply a value created during the evaluation of an expression and them immediately applied to produce a BOOL value.

While your situation is unusual, creating a block to immediately apply it in the same expression, a similar situation occurs when you pass a block to another method, either directly or by storing it in a local variable and passing the variables value - no cycle is created.

If instead you created the same block but stored it into an instance variable (not a local variable), then self would reference the block, the block would reference self, and you would have a cycle. That is not in itself bad, it only becomes bad if the cycle is never broken, which causes a leak. However if at some point the cycle is broken, say by writing a different value into the instance variable, then the cycle never becomes an issue.

HTH

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related