To illustrate the saving of objects in Core Data, we'll be going over how to create new Entity objects as well as some persistence code. Eventually you'll be able to save and delete objects with the press of a few buttons:
Go ahead and open your core data xcdatamodeld file and add the following Card entity:
Once your entity is entered, go the the Editor menu and hit Create NSManagedObject Subclass:
This will generate the necessary classes in your Xcode project. With Xcode 12+, you can actually delete these files since they are managed by Xcode automatically.
struct MainView: View { @State private var shouldPresentAddCardForm = false // 1 @Environment(\.managedObjectContext) private var viewContext // 2 @FetchRequest( sortDescriptors: [NSSortDescriptor(keyPath: \Card.timestamp, ascending: true)], animation: .default) private var cards: FetchedResults<Card> var body: some View { NavigationView { ScrollView { // 3 if !cards.isEmpty { TabView { ForEach(cards) { card in CreditCardView() .padding(.bottom, 50) } } // ... } Spacer() .fullScreenCover(isPresented: $shouldPresentAddCardForm, onDismiss: nil) { AddCardForm() } } .navigationTitle("Credit Cards") .navigationBarItems(leading: HStack { addItemButton deleteAllButton }, trailing: addCardButton) } } private var deleteAllButton: some View { Button { cards.forEach { card in viewContext.delete(card) } do { try viewContext.save() } catch { } } label: { Text("Delete All") } } // 4 var addItemButton: some View { Button(action: { withAnimation { let viewContext = PersistenceController.shared.container.viewContext let card = Card(context: viewContext) card.timestamp = Date() do { try viewContext.save() } catch { // error handling } } }, label: { Text("Add Item") }) }}struct MainView_Previews: PreviewProvider { static var previews: some View { let viewContext = PersistenceController.shared.container.viewContext MainView() // 5 .environment(\.managedObjectContext, viewContext) }}