Swift Struct Memory Leak

前端 未结 4 1881
轻奢々
轻奢々 2021-01-30 09:05

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

4条回答
  •  失恋的感觉
    2021-01-30 09:32

    You can solve the problem by creating a weak reference to the object which is captured by the closure.

    Here is your example without memory leak:

    import Foundation
    import RxSwift
    
    struct WithoutLeak {
    
        var someState: String = "initial value"
        var someVariable: Variable = Variable("some stuff")
    
        let bag = DisposeBag()
    
        mutating func someFoo() {
    
            weak let weakSomeState = someState // <-- create a weak reference outside the closure
    
            someVariable.subscribeNext { person in
    
                weakSomeState = "something" // <-- use it in the closure
            }
            .addDisposableTo(bag)
        }
    }
    

提交回复
热议问题