我的调用错误:调用中的参数标签不正确(有 'key:',预期 'coder:')

Error in my call : Incorrect Argument Label In Call (have 'key:', expected 'coder:')

我在对 Swift 中的 table 视图单元格进行排序的方法中收到一个错误。

错误来自 func loadDataFromDatabase() 行:

let sortDescriptor = NSSortDescriptor(key: sortPriority)

我的 table 视图控制器文件:

import UIKit
import CoreData

class noteTableViewController: UITableViewController {
    var notes = [Note]()

    var managedObjectContext: NSManagedObjectContext? {
        return (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    }

    func loadDataFromDatabase() {
        let settings = UserDefaults.standard

        let sortPriority = settings.string(forKey: Constants.kPriority)

        let context = appDelegate.persistentContainer.viewContext

        let request = NSFetchRequest<NSManagedObject>(entityName: "Note")

        let sortDescriptor = NSSortDescriptor(key: sortPriority)

        let sortDescriptorsArray = [sortDescriptor]

        request.sortDescriptors = sortDescriptorsArray

        do {
            notes = try context.fetch(request)
        } catch let errer as NSError {
            print("Could not fetch. \(error), \(error.userInfo)")
        }
    }
}

您的做法是将编译器与 init(coder:) 初始值设定项混淆。要使用你想要的初始化器,你还需要提供 ascending 参数:

let sortDescriptor = NSSortDescriptor(key: sortPriority, ascending: true)