Core Data - how to initiate my App settings properly?

Hello together,

i want to initiate my App settings by using core data.

E.g. the country - a list, which content fetched from a Firestore database, shall be initiated by the users previous selection. The storage in core data works well, I do have problems with the initiation of the pickers binding.

Please look at the following code snippets. Hopefully the seniors can answer resp. help me immediately … :grinning:

Core Data entitites:

The AppSettings model:

import Foundation
import SwiftUI

class AppSettings: ObservableObject {
    
    // MARK: properties
    @Published var country: String

    
    init(country: String = "Österreich") {
        self.country = country
    }
}

The ScoreboardSettings+CoreData Class

import Foundation
import CoreData

@objc (ScoreboardSettings)
public class ScoreboardSettings: NSManagedObject {

}

The Settings View

import SwiftUI
import CoreData


struct SettingsView: View {
    
    // Acces viewContext to use Core Data
    @Environment(\.managedObjectContext) private var viewContext
    
    @EnvironmentObject var settings: AppSettings // populated by a Firestore database 
    @EnvironmentObject var model: ContentModel
    
    @FetchRequest(sortDescriptors: []) var coreData: FetchedResults<ScoreboardSettings>
    
    var body: some View {
        NavigationView {
                Form {
                    Section {
                        Picker ("Country", selection: $settings.country) {
                            ForEach(countries, id: \.self) {
                                Text($0)
                            }
                        }
                    }
                }
        }
        .onAppear {
            // parse database result and create list with supported countries
            for i in 0...model.countries.count-1 {
                countries.append(model.countries[i].name)
            }
            
            // fetch stored core data values
            initialzeAppsettingsWithCoreDataValues()
                    
        }
        .onDisappear{
            // store Appsettings in CoreData
            storeSettingsToCoreData(arg: settings)
        }
    }

    private func storeSettingsToCoreData(arg: AppSettings) {
        
        let core = ScoreboardSettings(context: viewContext)
        
        core.country = arg.country
        
        do {
            try viewContext.save()
        }
        catch {
            // Error with saving
        }
    }
    
    func initialzeAppsettingsWithCoreDataValues() {
        
        if coreData.country != nil {
            settings.country = coreData.country!
        }     
    }
}

The initializeApssetingsWithCoreDataValues() doesn’t work. I get the following error messages:

Referencing subscript ‘subscript(dynamicMember:)’ requires wrapper ‘Binding<FetchRequest.Configuration>’
Value of type ‘FetchedResults’ has no dynamic member ‘country’ using key path from root type ‘FetchRequest.Configuration’

Now my question:

how to connect the binding $settings.country with the fetched value from coreSettings.country? Or is there a better way to program?

Thanks and best regards

Peter

Peter did you find a solution for this? I am struggling with a similar problem. When my update view is displayed, I need to fill a TextField so I can allow the user to edit it. I can’t seem to get the value to display (or the TextField PERIOD). I have been struggling with this for days and have found no solution. I looked back at Chris’s core data video and example, plus the recipe app with added core data but he never does an update! So there are no examples from this site that I can find. I also have Toggles that need to be set with core data values.

Hello jhcarter,

I haven’t found a solution for this problem. But I solved this issue by switching towards the class UserDefaults. With the user of the property Wrapper AppStorage it was pretty simple to store and read my (small) informations. As long as you don’t have to store a lot of data, it’s a perfect solution - e.g.: user settings, etc. …

Hope this information helps.

Thank you for responding! I have just about given up on this as I have scoured this site and the internet for a solution. It’s very frustrating and seems like something most apps would need to do! I’m a little disappointed that the two core data lessons on this site never illustrated updating data from core data. I did manage to get the toggles working and I can display my core data values in a plain Text box, but the TextField still eludes me. I get messages about the values being “get only properties” when I try to store new information in them. As for the UserDefaults, I have too much data with multiple arrays, so I don’t think it would work for me. Again, thank you so much for replying!