Home > Blockchain >  How to save data in array
How to save data in array

Time:09-26

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.

CodePudding user response:

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")
            }
        }
    }
   // ...
  • Related