Post

Replies

Boosts

Views

Activity

Memory not decreasing in SwiftUI when objects removed from array
I have replicated this issue with very little code that you can run below. When clicking the plus button several times you will see the memory increase as the array grows in size (as expected), but never decreases when objects are removed (even if we allocate the array reference to a new array) why is this? import SwiftUI struct ContentView: View { @ObservedObject var vechicleVM = vehicleViewModel() var body: some View { Button(action: { vechicleVM.addVehicle()}) { Image(systemName: "plus.circle") } Button(action: {vechicleVM.removeVehicle()}) { Image(systemName: "minus.circle") } } } import Foundation import Combine class vehicleViewModel : ObservableObject { @Published var ownedVehicles = [Vehicle]() private var cancellables = SetAnyCancellable() init(){ VehicleRepository.sharedInstance.$ownedVehicles.map { vehicle in vehicle } .assign(to: \.ownedVehicles, on: self) .store(in: &cancellables) } func addVehicle(){ VehicleRepository.sharedInstance.addVehicle() } func removeVehicle(){ VehicleRepository.sharedInstance.removeVehicle() } } struct Vehicle { var name: String var userHas: Bool } class VehicleRepository { //Singleton as this repo is used across many different views static let sharedInstance = VehicleRepository() @Published var ownedVehicles = [Vehicle]() // Adds 1000 vehicles to ownedVehicles (to increase memory used) func addVehicle(){ for i in 1...1000 { ownedVehicles.append(Vehicle(name: "", userHas: false)) } print(ownedVehicles.count) } // Removes 1000 vehicles to ownedVehicles (memory does not decrease?) func removeVehicle(){ for i in 1...1000 { if ownedVehicles.count 0 { //None of the following reduces memory //ownedVehicles = [Vehicle]() //ownedVehicles.remove(at: 0) //ownedVehicles.removeAll(keepingCapacity: false) } } print(ownedVehicles.count) } }
2
0
709
Apr ’21