Reputation: 962
I have a game with 500 records in core data. Each record has an id. They are all unique from 1 to 500.
In Swift 4 or 5, how do I sort the results of this fetch request? I need to sort ascending by prize.id. Thanks in advance.
func checkPrizes() {
trace("checkPrizes")
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let request: NSFetchRequest<Prize> = Prize.fetchRequest()
//finding specific record
let context = appDelegate.persistentContainer.viewContext
outputText.text = ""
do {
prizes = try context.fetch(request)
// try context.save()
for item in prizes {
print("Prize amount: \(item.amount!)")
outputText.text = item.amount!
print("Prize id: \(item.id!)")
outputText.text = item.id!
print("Prize region: \(item.region)")
outputText.text = String(item.region)
print("Prize won: \(item.won)")
// outputText.text.append(String(item.won) + "\n")
}
print("CheckPrizes count: \(prizes.count)")
outputText.text = "CheckPrizes count: \(String(prizes.count))"
} catch {
print("Failed to retrieve record")
print(error)
}
}
Upvotes: 0
Views: 912
Reputation: 8517
If you got your NSFetchRequest
, you can use sort var sortDescriptors: [NSSortDescriptor]?
, which is the sort descriptor of your fetch request.
request = [NSSortDescriptor(key: "id", ascending: true)]
Or you can just sort the array after your FetchRequest is completed.
Upvotes: 2
Reputation: 962
let sort = NSSortDescriptor(key: "id", ascending: true)
request.sortDescriptors = [sort]
Upvotes: 0