Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to save data in array

import Foundation
import SwiftUI



struct Person: Identifiable, Codable{
    var id = UUID()
    let name: String
    var isFavorite: Bool
}

class People: ObservableObject{
    @Published var group = [Person]() {
        didSet {
            if let encoded = try? JSONEncoder().encode(peopleData){
                UserDefaults.standard.set(encoded, forKey: "peopleKey")
            }
        }
    }
    
    
    init(){
        if let savedItems = UserDefaults.standard.data(forKey: "peopleKey"),
           let decodedItems = try? JSONDecoder().decode([Person].self, from: savedItems) {
            group = decodedItems
        } else {
            group = peopleData
        }
    }
    
    var peopleData: [Person] = [
        Person(name: "Bob", isFavorite: false),
        Person(name: "John", isFavorite: false),
        Person(name: "Kayle", isFavorite: false),
        Person(name: "Alise", isFavorite: false)
    ]
    
}

I am tryn to save a chance on array. But when I relaunch its not saved.

import SwiftUI

struct ContentView: View {
    
    @StateObject var model = People()
    
    var body: some View {
        VStack(alignment: .leading, spacing: 10){
            Text(model.group[0].name)
                .opacity(model.group[0].isFavorite ? 1:0)
            Button(model.group[0].isFavorite ? "Remove from favorite" : "add to favorites") {
                model.group[0].isFavorite.toggle()
                   }
        }
        }

    
    }

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

I can toggle the isFavorite bool with button. But when I relaunch its not saved.
in the which part of this code I made a mistake and why its not working I can’t figure out.

I tried a lot of way for save data in array but all attempts was failed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

currently you are saving peopleData, where you should be saving group. So try using:

class People: ObservableObject{
    @Published var group = [Person]() {
        didSet {
            if let encoded = try? JSONEncoder().encode(group){ // <-- here group
                UserDefaults.standard.set(encoded, forKey: "peopleKey")
            }
        }
    }
   // ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading