xcode 我的SwiftUI FetchRequest没有显示任何项目,尽管有10个项目

kulphzqa  于 2023-01-18  发布在  Swift
关注(0)|答案(1)|浏览(148)

这是我的代码:

struct ServicesView: View {
    @FetchRequest(entity: Category.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Category.name, ascending: false)], animation: .easeIn) var results: FetchedResults<Category>

    var body: some View {
        List(results) { category in
            VStack(alignment: .leading, spacing: 3, content: {
                Text(category.name)
                    .font(.system(size: 12))
                    .foregroundColor(.white)
                Text("x\(category.services.count)")
            })
        }
        .overlay(
            Text(results.isEmpty ? "Nothing here" : "")
        )
        .onAppear {
            print("😋")
            print(Category.numberOfEntities())
        }
    }
}

控制台上显示:
😋
10
为什么单子上什么都没有?

数字是如何计算的?

extension NSManagedObjectContext {
    static func defaultContext() -> NSManagedObjectContext {
        CoreDataManager.shared.defaultContext!
    }
}

protocol Fetchable {
    associatedtype FetchableType: NSManagedObject = Self
    static func numberOfEntities() -> Int
}

extension Fetchable where Self: NSManagedObject {
    static var entityName: String {
        entity().name ?? ""
    }
    static func numberOfEntities() -> Int {
        let request = NSFetchRequest<FetchableType>(entityName: entityName)
        let context = NSManagedObjectContext.defaultContext()
        do {
            return try context.count(for: request)
        } catch let error as NSError {
            print("❌ Core Data Count Error \(error), \(error.userInfo)")
            return 0
        }
    }
}

我想问题就在这里,因为我没有给@Environment’s managedObjectContext赋值,我应该怎么做呢?

@main
struct Watch_AppApp: App {
    var body: some Scene {
        WindowGroup {
                TabView {
                    TimerView()
                    ContentView()
                    ServicesView()  // how do i assign here managed object context?
                    Text("4th page")
                }
                .tabViewStyle(PageTabViewStyle())
                .onAppear(perform: loadData) //load data, fetch categories from cloudkit and save to core data, is is fetched and saved
            }
    }
}
hs1ihplo

hs1ihplo1#

首先,您必须将ManagedObjectContext添加到您要从中获取数据的视图中。
您可以像这样将其添加到视图中:

struct ServicesView: View {
    // The context for your view
    @Environment(\.managedObjectContext) var viewContext

   @FetchRequest(entity: Category.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Category.name, ascending: false)], animation: .easeIn) var results: FetchedResults<Category>

    var body: some View {
        List(results) { category in
            VStack(alignment: .leading, spacing: 3, content: {
                Text(category.name)
                    .font(.system(size: 12))
                    .foregroundColor(.white)
                Text("x\(category.services.count)")
            })
        }
        .overlay(
            Text(results.isEmpty ? "Nothing here" : "")
        )
        .onAppear {
           print("😋")
           print(Category.numberOfEntities())
        }
    }
}

要从条目视图传递上下文,必须从PersistenceController获取上下文,如下所示:

@main
struct Watch_AppApp: App {
    var body: some Scene {
        WindowGroup {
            TabView {
                TimerView()
                ContentView()
                ServicesView()  
                    // Assign the context
                    .environment(\.managedObjectContext, PersistenceController.shared.container.context)
                Text("4th page")
            }
            .tabViewStyle(PageTabViewStyle())
            .onAppear(perform: loadData) //load data, fetch categories from cloudkit and save to core data, is is fetched and saved
        }
    }
}

您可以在这里找到Core Data的文档:https://developer.apple.com/documentation/coredata

相关问题