Swift Struct Memory Leak

前端 未结 4 1880
轻奢々
轻奢々 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:30

    The pattern of capturing self by an escaping closure in a writable context is now disallowed. The swift compiler will emit an error "Closure cannot implicitly capture a mutating self parameter". If the context is read-only, the value of self could be copied or shared and in either case there wouldn't be a reference cycle.

    0 讨论(0)
  • 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<String> = 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)
        }
    }
    
    0 讨论(0)
  • 2021-01-30 09:39

    For anyone still facing this issue.

    1. [weak self] is not possible because Struct is value type and not a Reference type, so no pointer as such.

    2. The main issue of leak here is you are trying to access the Struct property self.someState = something inside the completion block which will basically create a new copy of your structure on assignment.

    You should not access Struct Property inside completion block.

    0 讨论(0)
  • 2021-01-30 09:48

    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.

    As the Strong Reference Cycles for Closures section puts it:

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

    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.

    0 讨论(0)
提交回复
热议问题