这是我的代码:
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
}
}
}
1条答案
按热度按时间hs1ihplo1#
首先,您必须将
ManagedObjectContext
添加到您要从中获取数据的视图中。您可以像这样将其添加到视图中:
要从条目视图传递上下文,必须从
PersistenceController
获取上下文,如下所示:您可以在这里找到Core Data的文档:https://developer.apple.com/documentation/coredata