这就是我的代码:
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条答案
按热度按时间mefy6pfw1#
首先,您必须将
ManagedObjectContext
添加到您试图从中获取数据的视图中。你可以像这样把它添加到你的视图中:
字符串
要从入口视图传递上下文,必须从
PersistenceController
获取上下文,如下所示:型
您可以在此处找到Core Data的文档:https://developer.apple.com/documentation/coredata