试图在UserDefaults中保存一些数据,但我在视图中得到nil。我不知道问题出在哪里
这是我在ContentView中的代码:var saveButton: some View {
Button("Save Meal") {
let meal = Meal(name: self.mealGenerator.currentMeal!.name,
imageUrlString: self.mealGenerator.currentMeal!.imageUrlString,
ingredients: self.mealGenerator.currentMeal!.ingredients,
instructions: self.mealGenerator.currentMeal!.instructions,
area: self.mealGenerator.currentMeal!.area,
category: self.mealGenerator.currentMeal!.category)
self.savedMeals.meals.append(meal)
self.savedMeals.saveMeals()
}
这是我要保存的类:
class SavedMeals: ObservableObject {
@Published var meals: [Meal]
func saveMeals() {
if let encoded = try? JSONEncoder().encode(meals) {
UserDefaults.standard.set(encoded, forKey: "Meals")
}
}
init() {
if let meals = UserDefaults.standard.data(forKey: "Meals") {
if let decoded = try? JSONDecoder().decode([Meal].self, from: meals) {
self.meals = decoded
return
}
}
self.meals = []
}
}
我想在视图中列出:
struct SavedMealsView: View {
@ObservedObject var savedMeals: SavedMeals
var body: some View {
NavigationView {
List(savedMeals.meals) { meal in
Text(meal.name)
}
.navigationBarTitle("Saved Meals", displayMode: .inline)
}
}
}
无论您解码什么,您都可以在init结束时执行meals = []
。也许这样会更好:
init() {
if data = UserDefaults.standard.data(forKey: "Meals") {
do {
meals = try JSONDecoder().decode([Meal].self, from: meals)
} catch {
assertionFailure("Oops!")
meals = []
}
} else {
meals = []
}
}