It is a standard generated new Core Data project, only the attributes of the Item entity are modified.
extension Item: Identifiable {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Item> {
return NSFetchRequest<Item>(entityName: "Item")
}
@NSManaged public var id: UUID?
@NSManaged public var name: String?
}
Post
Replies
Boosts
Views
Activity
Here's the complete code (CoreDataTableApp.swift):
import CoreData
@main
struct CoreDataTableApp: App {
let persistenceController = PersistenceController.shared
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
}
}
}
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Item.name, ascending: true)],
animation: .default)
private var items: FetchedResults<Item>
@State private var selection = Set<Item.ID>()
var body: some View {
Table(items, selection: $selection) {
TableColumn("Name") {
Text($0.name ?? "NoName")
}
}
.padding()
.toolbar {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
private func addItem() {
withAnimation {
let newItem = Item(context: viewContext)
let count = items.count + 1
newItem.id = UUID()
newItem.name = "Test Name \(count)"
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
}
// MARK: Core Data
@objc(Item)
public class Item: NSManagedObject {}
extension Item: Identifiable {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Item> {
return NSFetchRequest<Item>(entityName: "Item")
}
@NSManaged public var id: UUID?
@NSManaged public var name: String?
}
struct PersistenceController {
static let shared = PersistenceController()
let container: NSPersistentContainer
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "CoreDataTable")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
}
}
Error found, CoreData editor generates code:
@nonobjc public class func fetchRequest() -> NSFetchRequest<Item> {
return NSFetchRequest<Item>(entityName: "Item")
}
@NSManaged public var id: UUID?
@NSManaged public var name: String?
}
but the UUID is not optional, so correction:
@NSManaged public var id: UUID
and the table works as expected.