简体   繁体   中英

Would this create a retain cycle?

I am learned about the retain cycle then I was watching this video tutorial but I felt the code he was writing contain retain cycle. So I thought to post is here to ask opinion. Below the code snippet :

        [UIView transitionWithView:self.view duration:.5 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
        self.myImageView.image = randomDog.image;
        self.BreedLabel.text = randomDog.breed;
        self.nameLabel.text = randomDog.name;
    } completion:^(BOOL finished) {

    }]; 

Because Inside the block self is being used and this block will hold on to self as its strong pointer.

I read it somewhere that if one need to use self in side of the block its always good practice to create weekSelf like

id (nonatomic, weak) weakSelf;
weakSelf = self;

and then use the weakSelf inside the block.

Please help me if I understood the concept correctly. Thanks in advance.

You don't have retain cycle problem in this case.

You do have retain cycle, but it is temporary and won't cause any problem.

The retain graph is like ( A -> B means A retain B)

self -> view -> animationBlock -> self

but after animation block is executed, it is destroyed and retain graph become

self -> view

and it is all good


Also the correct syntax to break retain cycle is

__weak __typeof__(self) weakSelf = self;
^ { // inside block
    __typeof__(self) strongSelf = weakSelf;
   // use strongSelf
}

or you can use @weakify and @strongify from libextobjc

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