快速保留周期和关闭

编程入门 行业动态 更新时间:2024-10-12 03:17:30
本文介绍了快速保留周期和关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经尝试了很多有关了解保留周期的研究.我似乎无法在示例中找到任何内容.我确实知道,如果我将属性设置为闭包,则会发生保留周期,并且需要使用弱函数或无主函数.但是我有两个示例,我想知道它们是否正确完成:预先感谢,我试图查看它们是否已经在stackoverflow上,但是找不到任何东西.

I have tried to do a lot of research on understanding retain cycles. I can't seem to find anything on my examples though. I do know that if i set a property to a closure then a retain cycle happens and need to use weak or unowned. But i have 2 examples that I would like to know if they are done correctly: Thanks in advance, I have tried to see if they are on stackoverflow already but couldn't find anything.

简单的动画

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

带有数组的动画

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) }

在这两个示例中,self是UIView的子类.我只想知道我做得正确,还是我也应该将imageView用作弱引用.谢谢.

In both of these examples self is a subclass of UIView. I would just like to know that I am doing it correctly or if I should be using the imageView as weak reference too. Thanks.

推荐答案

这两个都不会创建保留周期,因为该块未附加到self.此外,在保证使用寿命的情况下保留周期并不是世界上最糟糕的事情.

Neither of these will create retain cycles since the block is not attached to self. Additionally, retain cycles with guaranteed life span aren't the worst thing in the world.

让我们考虑一些例子. (对不起,我的移动速度不是特别强,所以我将恢复为obj-c.)

Let's consider some examples. (sorry, my swift isn't particularly strong, so I'm going to revert to obj-c.)

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

这会创建一个保留周期,因为在self保持引用的块中,self被引用(不是弱引用).

This creates a retain cycle because self is referenced (not weakly) within a block to which self holds a reference.

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

这不会创建保留周期,因为animations块已发送到系统-您的UIView子类不包含对该块的引用.

This does not create a retain cycle because the animations block is sent off to the system -- your UIView subclass doesn't hold a reference to the block.

旁注:关闭结束时不需要使用return,但是我想swift太荒谬了,并且试图有所帮助".另外,我不确定在动画过程中是否需要调用self.setNeedsDisplay(),因为它本身应该执行此操作...

Side note: You shouldn't need to have a return at the end of your closure, but I guess swift is ridiculous and tries to be "helpful". Also, I'm not sure you need to call self.setNeedsDisplay() during the animation since it should be doing that itself...

更多推荐

快速保留周期和关闭

本文发布于:2023-11-26 02:17:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632251.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:周期   快速

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!