Swift结构内存泄漏 [英] Swift Struct Memory Leak

查看:154
本文介绍了Swift结构内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在尝试尽可能使用Swift结构.我们还使用RxSwift,它具有带闭包的方法.当我们有一个结构创建一个引用 self 的闭包时,该结构将创建一个

We're trying to use Swift structs where we can. We are also using RxSwift which has methods which take closures. When we have a struct that creates a closure that refers to self, that creates a strong reference cycle.

import Foundation
import RxSwift

struct DoesItLeak {

    var someState: String = "initial value"
    var someVariable: Variable<String> = Variable("some stuff")

    let bag = DisposeBag()

    mutating func someFoo() {

        someVariable.subscribeNext { person in

            self.someState = "something"
        }
        .addDisposableTo(bag)
    }
}

我怎么知道这个?如果我创建100,000个DidItLeak对象并在每个对象上调用someFoo(),我相信我有100,000个具有强引用周期的对象.换句话说,当我删除包含那些对象的DoesItLeak数组时,这些对象将保留在内存中.如果我不调用someFoo(),就没有问题.

How do I know this? If I create 100,000 DoesItLeak objects and call someFoo() on each of them, I believe I have 100,000 objects with strong reference cycles. In other words, when I get rid of the DoesItLeak array containing those objects, the objects stay in memory. If I do not call someFoo(), there is no problem.

变量是一个类.因此,我可以通过使用xcode的Instruments的分配并在 Variable<字符串>

Variable is a class. So, I can see this memory issue by using xcode's Instruments' Allocations and filtering in Variable< String >

如果我尝试使用如下所示的[weak self],则会出现编译器错误:

If I try to use [weak self] such as in the following, I get a compiler error:

someVariable.subscribeNext { [weak self] person in

编译器错误为弱不能应用于非类类型"

The compiler error is "weak cannot be applied to non-class type"

在实/非示例代码中,我们通过self访问方法和变量,这是一个内存问题.

In real/non-example code, we access methods and variables via self and it's a memory issue.

如何在保持DoesItLeak结构的同时解决此内存问题?

感谢您的帮助.

推荐答案

Darren 放在注释中: DoesItLeak不能成为结构我们不能让DoesItLeak成为结构并安全地解决强参考周期问题.

As Darren put it in the comments: "DoesItLeak can't be a struct" We cannot have the DoesItLeak be a struct and safely resolve the strong reference cycle issue.

诸如结构之类的值类型存在于堆栈框架中.闭包和类是引用类型.

Value types like structs exist on the stack frame. Closures and classes are reference types.

作为封闭的强大参考周期"部分说:

之所以发生这种强烈的引用循环,是因为闭包(如类)是引用类型.

This strong reference cycle occurs because closures, like classes, are reference types.

由于该结构具有Variable ,并且使用subscribeNext将引用self的闭包存储到Variable类中,因此它会创建强引用循环.请参见自动引用计数 Apple文档.

Since the struct has the Variable class and the closure referring to self is stored into the Variable class using subscribeNext, it creates the strong reference cycle. See "Resolving Strong Reference Cycles for Closures" in Automatic Reference Counting Apple documentation.

这篇关于Swift结构内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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