简体   繁体   中英

Retain cycle concern

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM