迅速关闭-捕捉自我弱点 [英] Swift Closures - Capturing self as weak

查看:51
本文介绍了迅速关闭-捕捉自我弱点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Swift中解决基于闭包的强引用循环。

在下面的代码中,对象由拥有的视图控制器保留。 ProgressHUD UIView ,它也由拥有的视图控制器保留。每次调用完成处理程序时, ProgressHUD 都会泄漏。使用新的闭包捕获功能时,将self声明为弱或无主不能解决内存泄漏。

I am trying to resolve a closure based strong reference cycle in Swift.
In the code below, object is retained by the owning view controller. ProgressHUD is a UIView that's also retained by the owning view controller. ProgressHUD is leaked every time the completion handler is called. When using the new closure capture feature, declaring self as weak or unowned does not resolve the memory leak.

object.setCompletionHandler { [weak self] (error) -> Void in
    if(!error){
        self?.tableView.reloadData()
    }
    self?.progressHUD?.hide(false)
}

但是,如果我在闭包之外声明self的弱var,它可以修复内存泄漏,就像这样:

However, if I declare a weak var for self outside of the closure, it fixes the memory leak, like this:

weak var weakSelf = self
object.setCompletionHandler { (error) -> Void in
    if(!error){
        weakSelf?.tableView.reloadData()
    }
    weakSelf?.progressHUD?.hide(false)
}

关于为什么它不能与Swift捕获一起使用的任何想法?

Any ideas as to why this is not working with Swift capturing?

推荐答案

如果将闭包分配给类实例的属性,并且闭包通过引用该实例或其成员来捕获该实例,则将创建一个强大的引用周期在关闭和实例之间。 Swift使用捕获列表来打破这些强大的参考周期。 Apple来源

If you assign a closure to a property of a class instance, and the closure captures that instance by referring to the instance or its members, you will create a strong reference cycle between the closure and the instance. Swift uses capture lists to break these strong reference cycles. source Apple

sketchyTech来源首先,重要的是很明显,整个问题仅涉及到将闭包分配给类实例的属性 的闭包。请牢记每个规则。
规则:

source sketchyTech First, it is important to make clear that this whole issue only concerns closures where we are assigning "a closure to a property of a class instance". Keep this in mind with each rule. The rules:


  1. 如果类实例或属性是可选的,请使用弱捕获

  2. 如果类实例或属性是非可选的并且永远不能设置为nil,则使用unown

  3. 您必须...使用in关键字,即使您省略了参数名称,参数类型和返回类型

在回答您的问题时,应该没有保留周期。

In answear to your question there should be no retain cycle.

这篇关于迅速关闭-捕捉自我弱点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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