SwiftUI not Releasing Memory for Deleted Cells in List

Viewed 784

If you create a list of the following view as rows:

struct ImageCellView: View {
    let image: UIImage

    init(image: UIImage) {
        self.image = image
    }

    var body: some View {
        return Image(uiImage: image).frame(height: 128).clipped()
    }
}

After cells are deleted, memory for UIImage is not released until new cells are added. Looking at the memory graph we can figure out that AGGraphStorage is holding reference for this:

Even if adding new cells can somehow free memory, UIImage is leaked occasionally:

Is this a bug in SwiftUI? Is there any way to get rid of this behavior?

1 Answers

Is this a bug in SwiftUI?

No, it is not. List caches rows for reuse & performance purpose.

Is there any way to get rid of this behavior?

Yes,

a) don't keep UIImage in member

b) manage UIImage in some other place and in struct keep it as weak var image: UIImage?

c) handle this in row's .onDisappear

d) ignore this, because List caches no more rows than fit on screen, so it will be reset when this row is used for other image

My preferable are a) and d), depending on use-case.

Related