SwiftUI 预览版不适用于 Core Data

Joh*_*ohn 2 core-data swift swiftui

我一直在尝试让详细视图正常工作,但是当从列表中给出当前所选项目的预览参数时,它一直给我一个错误Cannot convert value of type 'Item.Type' to expected argument type 'Item'

这是详细视图

import SwiftUI
import CoreData

struct FishDetailView: View {

    var item: Item

    @State var image : Data = .init(count: 0)
    
    var body: some View {
        Text(item.title ?? "")
        Text(item.details ?? "")
        Image(uiImage: UIImage(data: item.imageData ?? self.image)!)
            .resizable()
            .frame(width: UIScreen.main.bounds.width - 34, height: 210)
            .cornerRadius(15)
    }
}

struct FishDetailView_Previews: PreviewProvider {
    static var previews: some View {
        
        FishDetailView(item: Item) **<--- THE ERROR HAPPENS HERE**
    }
}
Run Code Online (Sandbox Code Playgroud)

内容视图.swift

import SwiftUI
import CoreData

struct ContentView: View {
    // MARK: - PROPERTY

    @State var title: String = ""
    @State private var showSheet: Bool = false
    @State var image : Data = .init(count: 0)
    @Environment(\.managedObjectContext) var viewContext

        @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
        animation: .default)
    private var items: FetchedResults<Item>
    
    // MARK: - FUNCTION
    private func deleteItems(offsets: IndexSet) {
        withAnimation {
            offsets.map { items[$0] }.forEach(viewContext.delete)

            do {
                try viewContext.save()
            } catch {
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }
    
    //: MARK - BODY

    var body: some View {
        NavigationView {
            VStack {
              
                List {
                    ForEach(items, id: \.self) { item in
                        NavigationLink(destination: FishDetailView(item: item)) {
                            Image(uiImage: (UIImage(data: item.imageData ?? self.image) ?? UIImage(systemName: "photo"))!)
                                .resizable()
                                .frame(width: UIScreen.main.bounds.width - 34, height: 210)
                                .cornerRadius(15)
                            HStack {
                                Text("\(item.details ?? "")")
                                
                            }//:HSTACK
                        }
                        // TODO: Insert timestamp here with .footnote font
                        }
                    }
                    
                    if showSheet {
                        AddFishView()
                    }
                }//: LIST
                .navigationBarTitle("Fishes", displayMode: .large)
                .navigationBarItems(trailing: Button(action: {
                    self.showSheet.toggle()
                })
                   {
                    Image(systemName: "camera.fill")
                })
                .sheet(isPresented: self.$showSheet) {
                    AddFishView()
                }
            } //: VSTACK
        } //: NAVIGATION
    }

// MARK: - PREVIEW

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        let persistenceController = PersistenceController.shared
        ContentView().environment(\.managedObjectContext, persistenceController.container.viewContext)
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我删除代码的预览部分,详细视图确实可以工作,但它并不是很理想,因为我想看看我在做什么,而不必每次进行更改时都在模拟器中打开应用程序。

我似乎无法弄清楚为什么会这样或如何解决它。有脑子比较好的人可以帮忙吗?

代码有点混乱,因为这只是我正在做的一个测试,我将用户图像保存到核心数据中。

编辑:已经尝试过建议的方法,但似乎没有解决我的问题PreviewProvider 和 ObservedObject 属性

这是 Item 实体 实体形象

mal*_*hal 5

import SwiftUI
import CoreData

struct FishDetailView: View {

    @ObservedObject var item: Item

    var body: some View {
        Text(item.title ?? "")
        ...
        // fyi your image should be a transformable attribute on the Item entity
    }
}

struct PreviewTestView_Previews: PreviewProvider {
    
    static var firstItem: Item? {
        let context = PersistenceController.preview.container.viewContext
        let fetchRequest = Item.fetchRequest()
        fetchRequest.fetchLimit = 1
        let results = try? context.fetch(fetchRequest)
        return results?.first
    }
    
    static var previews: some View {
        if let firstItem {
            FishDetailView(item: firstItem)
        }
        else {
            Text("Item not found")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)