swift core data order by code example

Example: swift core data order by

func sortlist(){

    //1
    guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
    }

    let managedContext =
        appDelegate.persistentContainer.viewContext

    //2
    let fetchRequest =
        NSFetchRequest<NSManagedObject>(entityName: "User")
    let sort = NSSortDescriptor(key: "date", ascending: false)
    fetchRequest.sortDescriptors = [sort]

    //3
    do {
        let  langugeCodes = try managedContext.fetch(fetchRequest)
        for result in langugeCodes as [NSManagedObject] {
            var   username:String = result.value(forKey: "username")! as! String

            print("username==>",username)


        }


    } catch let error as NSError {
        print("Could not fetch. \(error), \(error.userInfo)")
    }
}

Tags:

Misc Example