Swift 4、Core Data,我如何对fetch请求进行排序?

Swift 4 and Core Data, how do I sort fetch request?

我有一个核心数据有500条记录的游戏。每条记录都有一个ID。它们从 1 到 500 都是唯一的。

在Swift4或5中,如何对这个fetch请求的结果进行排序?我需要按 prize.id 升序排序。提前致谢。

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)
            }
    }
let sort = NSSortDescriptor(key: "id", ascending: true)
        request.sortDescriptors = [sort]

如果您得到 NSFetchRequest,您可以使用排序 var sortDescriptors: [NSSortDescriptor]? ,这是您的获取请求的排序描述符。

request = [NSSortDescriptor(key: "id", ascending: true)]

或者您可以在 FetchRequest 完成后对数组进行排序。