1
votes

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.

1
It is perfectly ok to use self inside a block. Especially if its a simple animation block (if it were a GCD block, it could be more complicated).Cutetare

1 Answers

3
votes

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