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

3b6akqbq  于 2023-08-07  发布在  Swift
关注(0)|答案(1)|浏览(114)

这就是我的代码:

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
            }
    }
}

mefy6pfw

mefy6pfw1#

首先,您必须将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

相关问题