0

i have a strange memory leak with this code:

class Test: ObservableObject {
    @Published var test:[TestStruct] = []

    func getTest() {
        guard let url = URL(string: "https://www.test.com") else {
            return
        }
        URLSession.shared.dataTask(with: url) {(data,_,_) in
            let testReturn = try!
                JSONDecoder().decode([TestStruct].self, from: data!)
            DispatchQueue.main.async {
                withAnimation{
                    self.test = testReturn
                }
            }
        }.resume()
    }
}




struct testView: View {

    @EnvironmentObject var testVar: Test

    var body: some View {
    VStack{
        ForEach(self.testVar.test) { TestMe in
            Text("print test")
        }
    }
    }
}

when the func getTest() is called many times the forEach loop increase the memory. When the EnvironmentObject testVar is updated by a new Json call it does not create new instances but simply updates the foreach loop

I have no idea what can create this problem because the code seems to me correct. Has anyone had similar experiences?

Thanks so much

Stefano Vet
  • 567
  • 1
  • 7
  • 18
  • the strange thing is that memory only increases when there is a new result. If the json result has already been fetched, the foreach does not increase the memory. strange – Stefano Vet Apr 26 '20 at 11:10
  • Where do you call `getTest()` ? – Nicolas Mandica Apr 26 '20 at 14:49
  • inside forEach loop a view is called - ForEach(self.testVar.test) { TestMe in TestNewView() }. Inside TestNewView, getTest() in called on onAppear { getTest() } for the first load. getTest() is also call from a button like self.testVar.getTest() and update the result but cause memory leak issue. Thanks Nicolas! – Stefano Vet Apr 26 '20 at 14:53
  • I also tried profile instruments but it does not report any leak. It seems that every update changes the foreach results but keeps all previous results in memory. In fact, redoing a request previously made does not increase memory, only new requests – Stefano Vet Apr 26 '20 at 17:12

0 Answers0