Quickly save loops and closures

I tried to do a lot of research on understanding conservation cycles. However, I cannot find anything in my examples. I know that if I set the property to close, then the save cycle is saved and should use weak or inactive. But I have 2 examples that I would like to know if they are executed correctly: in advance, I tried to check if they are already in stackoverflow, but did not find anything.

Simple animation

UIView.transitionWithView(self, duration: 5, options: .TransitionCrossDissolve, animations: { [weak self] in self?.setNeedsDisplay() return }, completion: nil) 

Array animation

 for imageView in self.townImages { UIView.transitionWithView(imageView, duration: 0.3, options: .TransitionCrossDissolve, animations: { () -> Void in imageView.image = UIImage(named: self.getImages()[count++]) }, completion: nil) } 

In both of these examples, self is a subclass of UIView . I would just like to know that I am doing this correctly, or if I should use imageView as a weak link. Thanks.

+6
source share
1 answer

None of them will create save cycles, since the block is not bound to self . In addition, maintaining cycles with a guaranteed service life is not the worst thing in the world.

Let's look at some examples. (Sorry, my fast is not particularly strong, so I will return to obj-c.)


 - (void)doSomething:(void(^)())block { self.block = block; } // elsewhere [self doSomething:^{ self.someProperty = 5; }]; 

This creates a save loop because self refers (not weakly) within the block to which self contains a reference.


 [UIView transitionWithView:self duration:5, options:UIViewAnimationOptionTransitionCrossDissolve animations:^{ [self setNeedsDisplay]; } completion:nil]; 

This does not create a save loop because the animations block is sent to the system - your UIView subclass UIView not contain a reference to the block.


Side note . You do not need to have return at the end of your closure, but I think swift is ridiculous and trying to be "useful." Also, I'm not sure if you need to call self.setNeedsDisplay() during the animation, as it should do it by itself ...

+2
source

Source: https://habr.com/ru/post/978203/


All Articles