简体   繁体   中英

Why do I have a possible retain cycle warning

I have the following block declared in a .h

@property (strong, nonatomic) void(^setHandedness)(BOOL hand);

it is defined in the matching .m

 setHandedness = ^(BOOL hand){
    _isRightHanded = hand;
};

and is passes to a child view controller which has the same form of block declared. Except with weak

@property (weak, nonatomic) void(^setHandedness)(BOOL hand);

Replacing strong with weak removes the warning. But I don't understand why?

the block is then called in the child view controller

setHandedness(handedness);

I have a warning telling me self is likely to cause a retain cycle? any ideas. Cheers.

The reason for the warning is this:

  1. Your object retains the block in the property.
  2. Your block retains your object because it accesses an instance variable.

Now you have two objects referencing each other. Even if no one else references them they will keep each other alive and never be deallocated.

Here is a quote from Apple's documentation for blocks and variables

If you access an instance variable by reference, self is retained;

Your second view controller has nothing to do with your retain cycle.

You have a possible retain cycle because it is usually the case that when the parent points to the child with a strong pointer, and the child points to the parent with another strong pointer, they will keep themselves alive and will never get dealocated (thats how ARC works). When you replace the child pointer for a weak one then this will not happen.

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