NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

Memory not decreasing in SwiftUI when objects removed from array

Forums > SwiftUI

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?

Video example here: https://imgur.com/a/gsos1SE

    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 = Set<AnyCancellable>()
    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)
    }

    }

   

I suspect that you may need to use deinit() in your class, and to check for circular references that would prevent memory, for array elements, from being deallocated. If a reference to a deleted array element remains through a sneak path, then the system cannot release the memory.

There is a lot to understand regarding how SwiftUI specifically handles memory allocation, deallocation and recovery, and I am still learning too.

Here is a link I found elsewhere, describing the way SwiftUI handles strong, weak and unowned memory references - Memory management in SwiftUI

   

You might want to read Apple Developer Documention - Growing the Size of an Array. By the look of it that you allocate memory but you need to reset when when capacity changes.

   

Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!

Get started now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.