如何进行CoreData排序

时间:2019-01-28 19:28:14

标签: swift core-data

我正在使用CoreData构建应用程序。我想按日期对我的CoreData数据进行排序。我已经尝试过了:

func getData() {
  let request = NSFetchRequest<Session>(entityName: "Session")
  let sort = NSSortDescriptor(key: "date", ascending: false)
  request.sortDescriptors = [sort]

  do {
    sessions = try contains.viewContext.fetch(request)
    print("Got \(sessions.count) sessions")
    tableView.reloadData()
  } catch {
    print("Fetch failed")
  }
}

但是它显示以下错误:Use of unresolved identifier 'NSFetchRequest' by the request

1 个答案:

答案 0 :(得分:0)

首先,您需要一个NSManagedContext,它可能类似于:

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

当然还有返回的NSManagedObjects的变量:

var sessions: [NSManagedObject] = []

然后您需要像这样使用它:

func loadQuotes() {
   let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Session")
   let sort = NSSortDescriptor(key: "date", ascending: false)
   fetchRequest.sortDescriptors = [sort]
   do {
      sessions = try context.fetch(fetchRequest)
      } catch let error as NSError {
      print("Fetch failed")
   }
}