A preface.

This is the first note I’ve written about Swift UI.

This is really hard to do, because it’s new. Domestic documents are really very few, foreign documents are also very few, basically found out are UIKit. Official documents, is a long story, basically in, I want to achieve a function, and then go to search a variety of posts, screening out useless posts, find useful points, of course, is often not found useful posts, and then go to the tubing to see a variety of tutorials, and then found: Oh! That’s how it works! Then go to the official document search, look at the attributes, their own call call……

Light is this core data I toss about for nearly a week, and finally found that the original or official good…..

Tease yourself with Swift UI, and now it’s time to get down to business.

Core Data is Apple’s official local database, but the files it stores are actually SQLite files. It can be backed up and synced via iCloud, which I’ll write an extra document about in detail. .

2. Environmental

Here is my current environment:

  • System: MacOS Big Sur 11.4
  • Xcode: Version 12.5 (12E262)
  • Swift: 5.4

Three. Operation steps

1. Create a project

When creating a project, you can directly select the Use Core Data option, and Xcode will generate a related demo directly in ContentView.swift.

2. Review relevant documents

After creating it, check the file directory. Compared with not selecting Use Core Data, there will be several more files as follows:

  • <Your-Project-Name>.xcdatamodeId
  • Persistence.swift

Mysql > create core data table

Click on < your-project-name >.xcdatamodeid file to enter the page.

You can see that you have “Default CONFIGURATIONS” and “Itities”. You can see that you have “Configurations” and “Item”.

Then click on Item, and you can see its field, which has the default timestamp field.

To Add ENTITIES (table), click the Add Entity button at the bottom.

To add Attributes, click + in Attributes on the right, noting that the field type is selected.

For example, take the default Item example and add the username and age fields.

4. Work with Core Data at the code level

1) check

@Environment(\.managedObjectContext) private var viewContext @FetchRequest( sortDescriptors: [NSSortDescriptor(keyPath: \ item.timestamp, Ascending: true), animation:.default) private var items: fetchedResults <Item> // body

2) new

private func addItem() {
  withAnimation {
    let newItem = Item(context: viewContext)
    newItem.timestamp = Date()

    do {
      try viewContext.save()
    } catch {
      // Replace this implementation with code to handle the error appropriately.
      // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
      let nsError = error as NSError
      fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
    }
  }
}

Above is the new function automatically generated by Xcode. If you want to add a custom field, you can change it like this:

Private func addItem(username: String, age:); private func addItem(username: String, age:); Int16) { withAnimation { let newItem = Item(context: viewContext) newItem.username = username newItem.age = age newItem.timestamp = Date() do { try viewContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nsError = error as NSError fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } } }

3) delete

private func deleteItems(offsets: IndexSet) {
  withAnimation {
    offsets.map { items[$0] }.forEach(viewContext.delete)

    do {
      try viewContext.save()
    } catch {
      // Replace this implementation with code to handle the error appropriately.
      // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
      let nsError = error as NSError
      fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
    }
  }
}

4) summary

In the default generated code, there is a Toolbar that works on MacOS, but only editionButton () is available on iOS. For the sake of demonstration, add a Button here to add data.

When writing code in Xcode, the Canvas on the right will render the data in real time. The data in the list is not the data in Core Data, but the data in Persistence. Swift is generated by default. You can only manipulate core data when the simulator/physical machine is compiling and running.

Here is the modified contentView. swift file:

// // ContentView.swift // HelloKuari // // Created by Kuari on 2021/6/5. // import SwiftUI import CoreData struct ContentView: View { @Environment(\.managedObjectContext) private var viewContext @FetchRequest( sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)], animation: .default) private var items: FetchedResults<Item> var body: some View { VStack { List { ForEach(items) { item in Text("Tom: \(item.username!) age: \(item.age) time : \(item.timestamp! , formatter: itemFormatter)")}.onDelete(perform: deleteItems)} "tom", age: 12) }, label: { Text("Add Item") }) } } private func addItem(username: String, age: Int16) { withAnimation { let newItem = Item(context: viewContext) newItem.username = username newItem.age = age newItem.timestamp = Date() do { try viewContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nsError = error as NSError fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } } } private func deleteItems(offsets: IndexSet) { withAnimation { offsets.map { items[$0] }.forEach(viewContext.delete) do { try viewContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nsError = error as NSError fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } } } } private let itemFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .medium return formatter }() struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext) } }

Then click the Run button at the top left to compile and run.

You start with a blank space, and when you click the Add Item button, you start adding data.

Right swipe to delete the record, which is the onDelete method of List.

4. Link to the original text

https://github.com/Kuari/Blog…

Five epilogue.

This article is for beginners and is also a record of the mistakes I have made. Because of the lack of documentation and the lack of Swift development partners, I can only rely on my own exploration. If there is a big guy who has a better way, please give me your advice.

Continued record behind the trample pit……