Search code examples
iosswiftmemory-leakssubscription

Memory leaking in custom Subscribable class


After implementation of the custom Subscribable class in the project.

I receive memory leaking in the app.

Code of the class.

open class Subscribable<T> {
    private var _value: T?
    private var _subscribers: [(T?) -> Void] = []
    open var value: T? {
        get {
            return _value
        }
        set {
            _value = newValue
            for f in _subscribers {
                f(value)
            }
        }
    }

    public init(_ value: T?) {
        _value = value
    }

    open func subscribe(_ subscribe: @escaping (T?) -> Void) {
        if let value = _value {
            subscribe(value)
        }
        _subscribers.append(subscribe)
    }
}

I have assumption that _subscribers will hold strong references to the array.


Solution

  • I believe that by default properties are with a strong reference.

    https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-ID52

    Not specifying weak or unowned may create reference cycles.

    Also items in an array have a strong reference coming from that array as well.

    You might want to check out this

    https://marcosantadev.com/swift-arrays-holding-elements-weak-references/