通过 CoreData Xcode 进行崩溃预览

问题描述 投票:0回答:1

我已经被一个问题困扰了很长一段时间。我遵循以下教程:https://www.youtube.com/watch?v=O0FSDNOXCl0&t=672s 但是,我无法在预览中显示/创建数据模型条目,它会系统崩溃。这只适用于模拟器。我尝试了很多技术,但没有任何效果,我认为我的环境/FetchResult/CoreData 预览结构有问题...

感谢您的宝贵帮助! :)

import SwiftUI
import CoreData

struct ContentView: View {
    @Environment(.managedObjectContext) var managedObjContext
    @FetchRequest(sortDescriptors: [SortDescriptor(.date, order: .reverse)]) var food: FetchedResults<Food>
    @State private var showingAddView = false
    @State private var isEditing = false


    var body: some View {
        NavigationView {
            VStack(alignment: .leading) {
                Text("(Int(totalCaloriesToday())) Kcal (Today)")
                    .foregroundColor(.gray)
                    .padding(.horizontal)
                List {
                    ForEach(food) { food in
                        NavigationLink(destination: EditFoodView(food: food)) {
                            HStack {
                                VStack(alignment: .leading, spacing: 6) {
                                    Text(food.name!)
                                        .bold()

                                    Text("(Int(food.calories))") + Text(" calories")
                                        .foregroundColor(.red)

                                }
                                Spacer()
                                Text(calcTimeSince(date: food.date!))
                                    .foregroundColor(.gray)
                                    .italic()

                            }

                        }
                    }
                    .onDelete(perform: deleteFood)

                }
                .listStyle(.plain)

            }
            .navigationTitle("iCalories")
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button {
                        showingAddView.toggle()
                    } label: {
                        Label("Add Food", systemImage: "plus.circle")
                    }
                }
                ToolbarItem(placement: .navigationBarLeading) {
                    EditButton()
                }
            }
            .sheet(isPresented: $showingAddView) {
                AddFoodView()
            }
        }
        .navigationViewStyle(.stack)

    }

    private func deleteFood(offsets: IndexSet) {
        withAnimation {
            offsets.map { food[$0] }.forEach(managedObjContext.delete)

            DataController().save(context: managedObjContext)
        }
    }

    private func totalCaloriesToday() -> Double {
        var caloriesToday: Double = 0
        for item in food {
            if Calendar.current.isDateInToday(item.date!) {
                caloriesToday += item.calories
            }
        }

            return caloriesToday
        }
    }



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

    }
}
swift xcode swiftui core-data
1个回答
0
投票

感谢您的链接,但我不使用 PersistenceController。我使用 FoodModel.xcdatamodeld 创建自己的 CoreData 控制器名称 DataController ,它使用此代码,并且我无法在我的示例中使用您的答案。每次我使用 DataController.preview 时,Xcode 都找不到 .preview 或 .shared,而且我不知道该把它放在哪里...

import Foundation
import CoreData

class DataController: ObservableObject {
    let container = NSPersistentContainer(name:"FoodModel")

    init() {
        container.loadPersistentStores { desc, error in
            if let error = error {
                print("Failed to load the data \(error.localizedDescription)")
            }
        }
    }
    
    
    func save(context: NSManagedObjectContext) {
        do {
            try context.save()
            print("Data saved ! Wuhu !")
        } catch {
            print("We could not save the data")
        }
    }
    
    func addFood(name: String, calories: Double, context: NSManagedObjectContext) {
        let food = Food(context: context)
        food.id = UUID()
        food.date = Date()
        food.name = name
        food.calories = calories
        
        save(context:context)
    }
    
    func editFood(food: Food, name: String, calories: Double, context: NSManagedObjectContext) {
        food.date = Date()
        food.name = name
        food.calories = calories
        
        save(context: context)
    }
}
  
© www.soinside.com 2019 - 2024. All rights reserved.