Struct contains property with reference type/class causing memory leak

I have a struct that contains a property of class/reference type. The following code seems causing a memory leak

struct AStruct { // make it a class would work fine below
    ...
    var aReferenceProperty: AClass!
    ...
}
    
class MyViewController {
    ...
    func someMethod(item: AStruct) {
      self.setSomeClosure { [weak self] _ in // [weak self, unowned item]
        item // need to use the item struct property in closure
      }
    }
    ...
}

The aReferenceProperty memory in the struct seems not being released when it should in the above code.

If I changed the AStruct to make it class instead, then, I will be able to provide weak item in the closure capture list, that will release the memory correctly.

Is there any way other than changing the AStruct to class for releasing the memory correctly?

The instance cannot be released simply because the item got copied and a strong reference still exists.

You have basically only two options – convert AStruct to a reference type and capture it weakly (note that reference types inside value types are always problematic).

Second option – don’t use item in the closure and capture only the reference instead:

self.setSomeClosure { [weak self, week aReferenceProperty = item.aReferenceProperty] _ in
    aReferenceProperty?...
}

Leave a Comment