简体   繁体   English

我的 SwiftUI FetchRequest 虽然有 10 个项目但没有显示任何项目

[英]My SwiftUI FetchRequest display no items although there is 10 iteme

This is what I have in code:这是我在代码中的内容:

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

On console is displayed:在控制台上显示:

10 10

Why there is nothing on the list?为什么名单上什么都没有?

在此处输入图像描述

How number is calculated?数量是怎么计算的?

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

I suppose the issue is here, because I dont assign @Environment's managedObjectContext nowhere.我想问题就在这里,因为我没有在任何地方分配@Environment's managedObjectContext How should I do it?我应该怎么做?

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

First of all you have to add the ManagedObjectContext to your view from which you are trying to fetch the data from.首先,您必须将ManagedObjectContext添加到您试图从中获取数据的视图中。

You can add it like this to your view:您可以像这样将其添加到您的视图中:

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

To pass the context from your entry view you have to get the context from your PersistenceController , like so:要从入口视图传递上下文,您必须从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
        }
    }
}

You can find the documentation of Core Data here: https://developer.apple.com/documentation/coredata您可以在此处找到 Core Data 的文档: https://developer.apple.com/documentation/coredata

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM