Sorting CoreData Records by Creation Date

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

What have you tried?

The code you quoted has this:

	@FetchRequest(sortDescriptors: []) var students: FetchedResults<Student>

which provides a place to specify how to sort the fetch results, but doesn't actually specify any sorting.

So, have you tried adding a sort descriptor for the creation date in that sortDescriptors array?

Thank you for your reply. Yes and no. I've figured out that I can do it by having an additional Date attribute. So I've started with a new Xcode project by having a new Date attribute named createdAt. And code goes as follows.

import SwiftUI

struct ContentView: View {
	@Environment(\.managedObjectContext) var managedObject
	@FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Student.createdAt, ascending: true)]) var students: FetchedResults<Student>
	
    var body: some View {
		VStack {
			List(students) { student in
				Text(student.name ?? "")
			}
			Button {
				let firstNames = ...
				let lastNames = ...
				if let selectedFirstName = firstNames.randomElement(), let selectedLastName = lastNames.randomElement() {
					let newStudent = Student(context: managedObject)
					newStudent.id = UUID()
					newStudent.name = "\(selectedFirstName) \(selectedLastName)"
					newStudent.createdAt = Date() // <<<<<<<<<<<<<<<<<<<<<<
					try? managedObject.save()
				}
			} label: { 
				Text("Add")
			}
		}
    }
}

, which takes care of the sort issue. As for the older project shown above, I wonder if Core Data has a simple mechanism in reordering the records when the entity does not include an additional Date attribute? That was my initial question.

Sorting CoreData Records by Creation Date
 
 
Q