Skip to content

Heap allocation of Storage class when a View using @AppStorageCompat is recreated during a state change in parent View #6

Description

@malhal

Hi is there any way that you can prevent this heap allocation made every time a View struct is created that declares a @AppStoreCompat?

_value = Storage(value: value, store: store, key: key, transform: transform)

_value = Storage(value: value, store: store, key: key, transform: transform)

E.g. in the code below every time the button is tapped to increment the stateCounter the body is recomputed which results in ContentView2 being init which is using @AppStoreCompat so causes this heap allocation of a new instance of the Storage class. It seems unnecessary to recreate the Storage class and have it re-register KVO observing when the View hasn't changed since last time. Perhaps there is a way to store the key and use it for equality and then delay creation of the Storage class until DynamicProperty's update call (which I noticed you aren't using).

I should say that Apple's implementation has the same behaviour as yours right now, but I'm sure they will fix this soon.

import SwiftUI
import AppStorage

struct ContentView: View {
    @State var stateCounter = 0
    var body: some View {
        VStack {
            Text("\(stateCounter) Hello, world!")
            Button("Increment") {
                stateCounter = stateCounter + 1
            }
            ContentView2()
        }
        .padding()
    }
}

struct ContentView2: View {
    @AppStorageCompat("counter", store:UserDefaults.group) var storageCounter = 0
    
    var body: some View {
        VStack {
            Text("\(storageCounter) Hello, world!")
            Button("Increment") {
                storageCounter = storageCounter + 1
            }
        }
        .padding()
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions