1

If you create a very simple example that shows a lot of leaking object within the SwiftUI code if you nest NavigationView/List/ForEach and return different types of views in the ForEach closure.

import SwiftUI

class MyStateObject : ObservableObject {
    
    @Published var items:[Int]
    
    init() {
        self.items = Array(0..<1000)
    }
    
}

struct ContentView: View {
    
    @StateObject var stateObject = MyStateObject()
    
    var body: some View {
        NavigationView {
            List {
                ForEach(stateObject.items, id: \.self) { item in
                    
                    if(item % 2 == 0) {
                        Text("Even \(item)")
                    }
                    else {
                        Image(systemName: "xmark.octagon")
                    }
                    
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

I strongly suspect this is a bug in SwiftUI but I wanted to ask if I am doing anything wrong here.

You can see the leaks by attaching Instruments. It will show immediately and increase if you scroll through the list.

Interestingly, it seems the leaks don't happen if

  • you remove the NavigationView from the hierarchy.
  • you only supply one type of View in ForEach (and don't branch via if/else).
  • the list of items you want to show is small (100 does not seem to result in leaks).

(Tested on XCode 12.5 and iOS 14.5 Simulator and Device,)

Since in my app I am pretty much reliant on this kind of hierarchy, I am very open for some suggestions on how to avoid the leaking.

Nicolas
  • 755
  • 9
  • 22
  • I have answered a similar question here: https://stackoverflow.com/a/67611933/921573 – de. Jul 29 '21 at 19:53
  • I can't reproduce the leak using Xcode beta. can you show some diagnostics on the leak. what is the allocation of? – SeaSpell Jul 30 '21 at 15:41
  • I did file FB9333352. In XCode 13-beta3, it still shows up, in beta4 the leaks are gone. But I suspect this is a bug in Instruments beta4. – Nicolas Jul 31 '21 at 09:42
  • @Nicolas If the leak is gone in beta 4, wouldn't that make you think that they _fixed_ this bug in beta 4? – George Jul 31 '21 at 21:26
  • Because it is also gone if you build against a deployment target of 14.5 and run it on the 14.5 Simulator. (Ie. I am not using iOS 15 code at all, but the leak is still gone in Instruments.) – Nicolas Aug 01 '21 at 11:20

0 Answers0