I have followed a tutorial written by Hacking with Swift ( https://www.hackingwithswift.com/books/ios-swiftui/how-to-combine-core-data-and-swiftui) about Core Data in SwiftUI. The Entity name is Student. And it has two properties: name (String), id (UUID). And the following is my code.
import SwiftUI
struct CoreView: View {
@Environment(\.managedObjectContext) var managedObject
@FetchRequest(sortDescriptors: []) var students: FetchedResults<Student>
var body: some View {
VStack {
List(students) { student in
Text(student.name ?? "Unknown")
}
Button {
let firstNames = ["Gary", "Harry", "Elane", "Ray", "Nancy", "Jim", "Susan"]
let lastNames = ["Johns", "McNamara", "Potter", "Thompson", "Hampton"]
if let selectedFirstName = firstNames.randomElement(), let selectedLastName = lastNames.randomElement() {
let newStudent = Student(context: managedObject)
newStudent.id = UUID()
newStudent.name = "\(selectedFirstName) \(selectedLastName)"
try? managedObject.save()
}
} label: {
Text("Add")
}
}
}
}
struct CoreView_Previews: PreviewProvider {
static var previews: some View {
CoreView()
.environmentObject(DataController())
}
}
If I list all records and then add a new student to the list, the app will insert the last addition at a random row. I wonder if I can order these records by the creation date?
Muchos thankos