快速保留周期和关闭 [英] Swift Retain Cycles and Closures

查看:154
本文介绍了快速保留周期和关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在这两个示例中,selfUIView的子类.我只想知道我做得正确,还是我也应该将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...

这篇关于快速保留周期和关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆