Reputation: 3
I'm trying to sort an array. Inside the array are naamdeelnemer
, totaalpunten
etc.
When I print for a check the array returns [ ]
. Anyone who can help me?
import UIKit
import CoreData
var userArray:[Punten] = []
override func viewDidLoad() {
super.viewDidLoad()
userArray.sort { $0.naamdeelnemer! < $1.naamdeelnemer!}
print(userArray)
tableView.delegate = self
tableView.dataSource = self
self.fetchData()
self.tableView.reloadData()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let name = userArray[indexPath.row]
cell.textLabel!.text = name.naamdeelnemer! + " " + String(name.totaalpunten)
return cell
}
func fetchData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do {
userArray = try context.fetch(Punten.fetchRequest())
}
catch {
print(error)
}
}
Upvotes: 0
Views: 101
Reputation: 285092
You have first to fetch the data then sort them
self.fetchData()
userArray.sort { $0.naamdeelnemer! < $1.naamdeelnemer!}
However this is not CoreData like. Fetch the data passing a sort descriptor. This is much more efficient
func fetchData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let request : NSFetchRequest<Punten> = Punten.fetchRequest()
request.sortDescriptors = [NSSortDescriptor(key: "naamdeelnemer", ascending: true)]
do {
userArray = try context.fetch(request)
}
catch {
print(error)
}
}
and
userArray.sort { $0.naamdeelnemer! < $1.naamdeelnemer!}
Upvotes: 0
Reputation: 5470
You can use "NSSortDescriptor" on the request while fetching the data from Core Data. Please find sample code below:
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "TableName")
request.sortDescriptors = [NSSortDescriptor(key: "naamdeelnemer", ascending: true)]
Here, "TableName" is the name of table to fetch record. "naamdeelnemer" is the field on which the sorting can be done. ascending: parameter can be "true" or "false"
Upvotes: 1